I am looping through a list and would like to reference the loop index number in the key of a hash.
Example:
unit_type = Hash.new
index = 5
list.each do |x|
unit_type[:loop_[index]] = x
index = index 1
end
The resulting key hash value should be:
unit_type = {:loop_5 #> "test result"}
How can I pass the index number in the key title together with other text as shown above?
CodePudding user response:
i think we can use to_sym
list.each do |x|
unit_type["loop_#{index}".to_sym] = x
index = 1
end
CodePudding user response:
Ruby allows #{...}
interpolation for symbol literals. You could also utilize with_index
to inject an index right into the loop:
list = %w[a b c]
unit_type = {}
list.each.with_index(5) do |x, i|
unit_type[:"loop_#{i}"] = x
end
unit_type
#=> {:loop_5=>"a", :loop_6=>"b", :loop_7=>"c"}
Alternatively, via to_h
which creates a hash based on key-value pairs returned by the block:
list = %w[a b c]
unit_type = list.each.with_index(5).to_h { |x, i| [:"loop_#{i}", x] }
#=> {:loop_5=>"a", :loop_6=>"b", :loop_7=>"c"}