Reputation: 69
I have hash which is
hash = {"stars"=>"in the galaxy", "fin"=>"is for fish", "fish"=>"has fins"}
Now I have a find method
def find(value)
if hash.empty? == true
return {}
else
return hash
end
end
Now i want to do is- when executed find("fi")
, I want the method to return all the hash key+ value which contain fi
in the key. So an output such that would look like -
{"fin"=>"is for fish", "fish"=>"has fins"}
Please note "fi" is not fixed. It can be anything. Since Find method accepts an argument value
.
Any help or suggestion is appreciate. I tried hash#select. but wasnt so helpful. I am not really sure what to use here.
Upvotes: 2
Views: 8856
Reputation: 160551
I'd use something like:
hash = {"stars"=>"in the galaxy", "fin"=>"is for fish", "fish"=>"has fins"}
pattern = 'fi'
hash.select{ |k,v| k[pattern] }
# => {"fin"=>"is for fish", "fish"=>"has fins"}
Upvotes: 6
Reputation: 5773
hash.select {|k, _| k.include? str}
where str
is the string you're looking for.
Upvotes: 8