-1
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.

SRack
  • 11,495
  • 5
  • 47
  • 60

3 Answers3

1

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
Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
1

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.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
SRack
  • 11,495
  • 5
  • 47
  • 60
  • Keep in mind that [`Hash#symbolize_keys!`](https://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys-21) is part of the Rails "[activesupport](https://rubygems.org/gems/activesupport)" gem and this question is not tagged with `ruby-on-rails` – 3limin4t0r Aug 10 '18 at 11:50
  • Argh you're right. Really had in mind that was core Ruby. Will remove that section, thanks @JohanWentholt. – SRack Aug 10 '18 at 11:56
  • Did this help at all @SavageHolycow? – SRack Aug 14 '18 at 12:17
0

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
Rafid
  • 641
  • 1
  • 8
  • 20