Use Fetch To Find Value From The Hash

by

in

Using hash[] method we can return the value. It will return the value if the key exists, else it will return nil.
Using hash fetch method will also do the same but additionally, it will give few options like assigning a default value, executing block, etc.
Here are some examples

Don’ts

hash = { one: "one", two: "two", three: "three" } hash[:one] -> one\

Do’s

hash = { one: "one", two: "two", three: "three" } hash.fetch(:one) - > one

Don’ts

hash = { one: "one", two: "two", three: "three" } value = hash[:four] ? hash[:four] : 4 puts value -> 4
OR otherhash = { one: "one", two: "two", three: "three" } value = hash[:four] || 4 puts value -> 4

Do’s

hash = { one: "one", two: "two", three: "three" } value = hash.fetch(:four, 4) puts value - > 4

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *