Jorge Cuevas Jorge Cuevas - 3 months ago 5
Ruby Question

How to generate symbols inside a loop in ruby

I have a section of a web app that passes a hash of values like this for each of the

order_items
in an
order
.

Like this:

def example_method
values = {
amount_1: order_items.first.unit_price,
item_name_1: order_items.first.unit_price,
quantity_1: order_items.first.quantity,

amount_2 order_items.second.unit_price,
item_name_2: order_items.second.unit_price,
quantity_2: order_items.second.quantity,
}
end


I'm trying to generate a solution where I have a variable like
n = 1
and generate the symbols for each
order_item
using
n
like this:

def example_method
values = {
n=1
order_items.each do |item|
:"amount_#{n}" => item.unit_price,
:"item_name_#{n}" => item.name,
:"item_number_#{n}" => item.id,
:"quantity_#{n}" => item.quantity,
n += 1
end
end


I tried this syntax outside of the loop and it works perfectly to generate the symbols using the variable, the problem is that I get a Syntax Error when the code is inside the loop:

How can I achieve this behavior inside my code?

What am I missing?

#edit



Edit for a proposed solution:

values = {
# The rest of static values on the hash...
}

n = 1

items = order_items.each do |item|
{
"amount_#{n}".to_sym => item.unit_price,
"item_name_#{n}".to_sym => item.printer.name,
"item_number_#{n}".to_sym => item.id,
"quantity_#{n}".to_sym => item.quantity,
}
n += 1
end

values.merge(items)

Answer

please try this

n=1
order_items.each do |item|
  "amount_#{n}".to_sym => item.unit_price,
  "item_name_#{n}".to_sym =>  item.name,
  "item_number_#{n}".to_sym =>  item.id,
  "quantity_#{n}".to_sym =>  item.quantity,
  n += 1
end

#edit

items = order_items.each do |item|
  "amount_#{n}".to_sym => item.unit_price,
  "item_name_#{n}".to_sym =>  item.name,
  "item_number_#{n}".to_sym =>  item.id,
  "quantity_#{n}".to_sym =>  item.quantity,
  n += 1 
end

old_hash.merge(items)

maybe you could running this and merge with outside hash

edit 2

you can install gem 'pry' to a better debug solution. For more info check this videos RailsCast Pry Debug

values = {
  # The rest of static values on the hash...
}

n = 1

items = order_items.each do |item|
  {
    "amount_#{n}".to_sym => item.unit_price,
    "item_name_#{n}".to_sym =>  item.printer.name,
    "item_number_#{n}".to_sym =>  item.id,
    "quantity_#{n}".to_sym =>  item.quantity, 
  }
  n += 1
end
binding.pry # this will able a ruby shell prompt and you can execute your code and analyse the values
values.class # in pry prompt
items.class # in pry prompt
values.merge(items)

#edit 3

@items = {}

order_items.each do |item| 
  @items = { 
  "amount_#{n}".to_sym => item.unit_price, 
  "item_name_#{n}".to_sym => item.printer.name, 
  "item_number_#{n}".to_sym => item.id, 
  "quantity_#{n}".to_sym => item.quantity} 
   values = values.merge(@items) 
   n += 1 
end