items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
items = price
I'd like to be to call, for example: pickle #=> 6; tuna # => 5
and so on.
items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
items = price
I'd like to be to call, for example: pickle #=> 6; tuna # => 5
and so on.
It is not possible to dynamically create local variables.
You can do something like eval "abc = 123; puts abc"
but after that abc
is still undefined.
It is possible to change values of existing local variables:
items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
pickle = nil
tuna = nil
pasta_sauce = nil
beans = nil
soup = nil
local_binding = binding
items.zip(price).each do |var, val|
local_binding.local_variable_set var, val
end
puts pasta_sauce
# outputs 3
You probably want to do something different. You can for example dynamically create instance variables:
items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
items.zip(price).each do |var, val|
instance_variable_set "@#{var}", val
end
puts @pasta_sauce
# outputs 3
It's likely you'd be far better suited converting the two arrays to a hash to access, rather than using meta programming to set the variables (although @KimmoLehto provides a great answer should you choose that route).
As a much simpler way to create a hash of the two arrays:
my_hash = Hash[items.zip(price)]
# or
my_hash = items.zip(price).to_h
items.zip(price)
combines the arrays (see: zip
):
[["pickle", 6], ["tuna", 5], ["pasta_sauce", 3], ["beans", 2], ["soup", 2]]
And using Hash::[]
or to_h
converts to a hash:
{"pickle"=>6, "tuna"=>5, "pasta_sauce"=>3, "beans"=>2, "soup"=>2}
You can then access the keys using the standard hash syntax:
my_hash['pickle'] # => 6
Or convert to and OpenStruct
if you prefer to access the variables using a .
:
my_open_struct = OpenStruct.new(items.zip(price).to_h)
my_open_struct.pickle # => 6
Hope that helps.
you can create a new hash for aggregating those arrays.
items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
hash = {} # or Hash.new
items.each_with_index do |var, idx|
hash[var] = price[idx]
end
puts hash["pasta_sauce"] # 3
puts hash["pickle"] # 6