简体   繁体   中英

Ruby print array with variable name

I want to parse a array in such way it gives following output

arr1 = (1..5).to_a
arr2 = (4..10).to_a
arr3 = (10..20).to_a

(1..3).map do |i|
   puts arr#{i} # It will throw an error, I am looking a way to achieve this. 
end

Need to achieve above result in ruby .

You can do almost anything in Ruby. To get the value of a local variable in the current binding , you'd use local_variable_get :

arr1 = (1..5).to_a
arr2 = (4..10).to_a
arr3 = (10..20).to_a

(1..3).each do |i|
  puts binding.local_variable_get("arr#{i}")
end

But that's cumbersome and error prone.

If you want to iterate over objects, put them in a collection. If you want the objects to have a certain label (like your variable name), use a hash:

arrays = {
  arr1: (1..5).to_a,
  arr2: (4..10).to_a,
  arr3: (10..20).to_a
}

arrays.each do |name, values|
  puts "#{name} = #{values}"
end

Output:

arr1 = [1, 2, 3, 4, 5]
arr2 = [4, 5, 6, 7, 8, 9, 10]
arr3 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

If the names are not relevant, use an array as shown in max pleaner's answer .

The quick and dirty way is to use eval :

(1..3).map do |i|
   puts eval("arr#{i}")
end

but you should not do this in your code, it's non-idiomatic, slower, unsafe, and is not properly using data structures. A better way is to move the arrays into a parent array:

arrays = [
  (1..5).to_a,
  (4..10).to_a,
  (10..20).to_a
]

arrays.each { |arr| puts arr }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM