leaning diary Rails

【Learning Diary50】ハッシュからkey、value、配列データを取得する

Hash#key

Hash#key(引数)は、引数を値を持つKeyを返すメソッドです。

 

>> hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
=> {:price=>100, :order_code=>200, :order_date=>"2018/09/20", :tax=>0.8}
>> p hash.key 100
:price
=> :price
>> p hash.key 0.8
:tax
=> :tax

Hash#values

 

Hash#valuesは、レシーバの値を集めた配列を返します。引数は取りません。

 

>> hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
>> hash.values
=> [100, 200, "2018/09/20", 0.8]
>>

Hash#values_at

Hash#values_atは、引数に指定したkeyの値を配列で返します。

 

>> hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
=> {:price=>100, :order_code=>200, :order_date=>"2018/09/20", :tax=>0.8}
>> hash.values_at(:price,:tax)
=> [100, 0.8]
>> hash.values_at(:order_date)
=> ["2018/09/20"]

Hash#[]

Hash#[]は、引数にあったkeyが持つ値を返します。

 

>> hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
=> {:price=>100, :order_code=>200, :order_date=>"2018/09/20", :tax=>0.8}
>> hash.[](:price)
=> 100
>> hash.[](:tax)
=> 0.8
>> hash.[](:order_code)
=> 200
>>

 

 

-leaning diary, Rails