Reputation: 410
I have an array of hashes, all with the same keys, all with a key of id
. I need a comma delimited string of ids.
arr_widgets = []
widgets.each do |widget|
arr_widgets.push(widget['id'])
end
str_widgets = arr_widgets.join(',')
Upvotes: 0
Views: 249
Reputation: 110675
There is no need to create an intermediate array.
widgets = [
{"id"=>"dec"}, {"id"=>21}, {"id"=>2020}, {"id"=>"was"},
{"id"=>"the"}, {"id"=>"shortest"}, {"id"=>"day"}, {"id"=>"of"},
{"id"=>"the"}, {"id"=>"longest"}, {"id"=>"year"}
]
Note that two values are integers.
s = widgets.each_with_object(String.new) do |widget, s|
s << ',' unless s.empty?
s << widget["id"].to_s
end
puts s
#=> "dec,21,2020,was,the,shortest,day,of,the,longest,year"
Upvotes: 1
Reputation: 30056
Have you tried something like this?
str_widgets = widgets.map { |w| w['id'] }.join(',')
Upvotes: 4