如何从哈希数组中获取所需的哈希值

时间:2014-05-30 12:27:58

标签: ruby-on-rails ruby

我有一系列形式的哈希:

[{"status"=>"Unshipped", "city"=>"thane", "buyer_name"=>"abc", "name"=>"abc def", "countryCode"=>"IN", "payment_method"=>"COD", "order_type"=>"StandardOrder", "y_id"=>"r123", "phone"=>"12345", "state"=>"Maharashtra", "service"=>"Expedited", "address_1"=>"abc xyz", "address_2"=>"yyyy", "postalCode"=>"400607", "shipped_by_y"=>"false", "channel"=>"MFN", "amout"=>"350.00"}, {"status"=>"Unshipped", "city"=>"Chembur, Mumbai", "buyer_name"=>"xyz", "name"=>"xyz lmn", "countryCode"=>"IN", "payment_method"=>"Other", "order_type"=>"StandardOrder", "y_id"=>"r124", "phone"=>"12436", "state"=>"Maharashtra", "service"=>"Expedited", "address_1"=>"add 1", "address_2"=>"add 2", "postalCode"=>"400071", "shipped_by_y"=>"false", "channel"=>"MFN", "amout"=>"399.00"}]

从这个数组中我想选择为键y_id赋值的元素。 例如。如果我想获得'y_id' = 'r124'的元素,我应该得到:

{"status"=>"Unshipped", "city"=>"Chembur, Mumbai", "buyer_name"=>"xyz", "name"=>"xyz lmn", "countryCode"=>"IN", "payment_method"=>"Other", "order_type"=>"StandardOrder", "y_id"=>"r124", "phone"=>"12436", "state"=>"Maharashtra", "service"=>"Expedited", "address_1"=>"add 1", "address_2"=>"add 2", "postalCode"=>"400071", "shipped_by_y"=>"false", "channel"=>"MFN", "amout"=>"399.00"}

2 个答案:

答案 0 :(得分:5)

您应该使用find API。它返回与您查找的内容匹配的第一个元素,如果没有找到,则返回nil

arr.find { |element| element['y_id'] == 'r124' }

将返回:

{"status"=>"Unshipped", "city"=>"Chembur, Mumbai", "buyer_name"=>"xyz", "name"=>"xyz lmn", "countryCode"=>"IN", "payment_method"=>"Other", "order_type"=>"StandardOrder", "y_id"=>"r124", "phone"=>"12436", "state"=>"Maharashtra", "service"=>"Expedited", "address_1"=>"add 1", "address_2"=>"add 2", "postalCode"=>"400071", "shipped_by_y"=>"false", "channel"=>"MFN", "amout"=>"399.00"}

答案 1 :(得分:2)

你应该可以使用

arr.find { |i| i['y_id] == *value* }

将迭代您的哈希数组,其中i是任何给定的哈希值。 Select将返回一个对象数组,其中块将解析为true

因此,例如,如果您将r123作为传递,则会返回

{"status"=>"Unshipped", "city"=>"thane", "buyer_name"=>"abc", "name"=>"abc def", "countryCode"=>"IN", "payment_method"=>"COD", "order_type"=>"StandardOrder", "y_id"=>"r123", "phone"=>"12345", "state"=>"Maharashtra", "service"=>"Expedited", "address_1"=>"abc xyz", "address_2"=>"yyyy", "postalCode"=>"400607", "shipped_by_y"=>"false", "channel"=>"MFN", "amout"=>"350.00"}

获取哈希值。 (谢谢@BroiSatse)