在数组中加入键的值 - Ruby

时间:2021-08-24 21:17:23

I am noob in ruby and have an array of hashes as per below. Say my array is @fruits_list:

我是红宝石的菜鸟,并且有如下所示的一系列哈希。说我的数组是@fruits_list:

[
    {:key_1=>15, :key_2=>"Apple"}, 
    {:key_1=>16, :key_2 =>"Orange"}, 
    {:key_1=>17, :key_2 =>"Cherry"}
]

What I am looking for is to join the names of the fruits. I did @fruits_list[:key_2].join('|')

我正在寻找的是加入水果的名称。我做了@fruits_list [:key_2] .join('|')

and I am getting the error as "TypeError:no implicit conversion of Symbol into Integer"

我得到错误为“TypeError:没有将符号隐式转换为整数”

Please suggest.

请建议。

1 个解决方案

#1


3  

Use Array#collect first to collect names of fruits, then join them with a pipe | using Array#join

首先使用Array#collect收集水果的名称,然后用管道连接它们使用Array#join

@fruits_list = [
                  {:key_1=>15, :key_2=>"Apple"}, 
                  {:key_1=>16, :key_2 =>"Orange"}, 
                  {:key_1=>17, :key_2 =>"Cherry"}
               ]
@fruits_list.collect { |hsh| hsh[:key_2] }.join("|")
# => "Apple|Orange|Cherry"

@fruits_list is an array of hash(s). Elements of an array can be accessed via the integer indexes only. But you tried to access it with a symbol :key_2, thus it raised an error as "TypeError:no implicit conversion of Symbol into Integer".

@fruits_list是一个哈希数组。只能通过整数索引访问数组的元素。但是您尝试使用符号:key_2访问它,因此它引发了一个错误,如“TypeError:没有将Symbol隐式转换为整数”。

#1


3  

Use Array#collect first to collect names of fruits, then join them with a pipe | using Array#join

首先使用Array#collect收集水果的名称,然后用管道连接它们使用Array#join

@fruits_list = [
                  {:key_1=>15, :key_2=>"Apple"}, 
                  {:key_1=>16, :key_2 =>"Orange"}, 
                  {:key_1=>17, :key_2 =>"Cherry"}
               ]
@fruits_list.collect { |hsh| hsh[:key_2] }.join("|")
# => "Apple|Orange|Cherry"

@fruits_list is an array of hash(s). Elements of an array can be accessed via the integer indexes only. But you tried to access it with a symbol :key_2, thus it raised an error as "TypeError:no implicit conversion of Symbol into Integer".

@fruits_list是一个哈希数组。只能通过整数索引访问数组的元素。但是您尝试使用符号:key_2访问它,因此它引发了一个错误,如“TypeError:没有将Symbol隐式转换为整数”。