jonypony3
jonypony3

Reputation: 410

How can I shorten the following Ruby code?

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

Answers (2)

Cary Swoveland
Cary Swoveland

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

Ursus
Ursus

Reputation: 30056

Have you tried something like this?

str_widgets = widgets.map { |w| w['id'] }.join(',')

Upvotes: 4

Related Questions