When i was learning about pattern matching in ruby, i came across this issue
<code>hash = { name: 1, age: 21, location: "NYC" }
case hash
in {name: String => x, age:y, location:z}
puts "Name: #{x}, Age: #{y}, Location: #{z}"
in {name: x, age:y}
puts "Name: #{x}, Age: #{y}"
else
puts "Invalid pattern"
end
</code>
<code>hash = { name: 1, age: 21, location: "NYC" }
case hash
in {name: String => x, age:y, location:z}
puts "Name: #{x}, Age: #{y}, Location: #{z}"
in {name: x, age:y}
puts "Name: #{x}, Age: #{y}"
else
puts "Invalid pattern"
end
</code>
hash = { name: 1, age: 21, location: "NYC" }
case hash
in {name: String => x, age:y, location:z}
puts "Name: #{x}, Age: #{y}, Location: #{z}"
in {name: x, age:y}
puts "Name: #{x}, Age: #{y}"
else
puts "Invalid pattern"
end
In the above code, i expected Invalid pattern to be printed on the screen(since the name keyword value is an integer), but when i ran in in replit, the value printed on the console was Name: 1, Age: 21
How does this happen?
For the second in condition, the hash must only have name and age, but in the hash provided, it has name, age and location
New contributor
Regal Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.