Ruby value of a hash key?

后端 未结 6 2156
暖寄归人
暖寄归人 2021-01-31 08:43

I\'ve got a list of values that are in a Ruby hash. Is there a way to check the value of the key and if it equals \"X\", then do \"Y\"?

I can test to see if the hash ha

6条回答
  •  执念已碎
    2021-01-31 08:54

    This question seems to be ambiguous.

    I'll try with my interpretation of the request.

    def do_something(data)
       puts "Found! #{data}"
    end
    
    a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
    a.each { |key,value| do_something(value) if key == 'x' }
    

    This will loop over all the key,value pairs and do something only if the key is 'x'.

提交回复
热议问题