Here is what i am trying to do, but it is not working.
array = [1,2,3,4,5]
array.each do |val1, val2, val3, val4, val5|
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics ${val5}"
end
Here is what i am trying to do, but it is not working.
array = [1,2,3,4,5]
array.each do |val1, val2, val3, val4, val5|
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics ${val5}"
end
array.each is going to execute the block (the part between do and end) once for every element in array, each time using that element as the first argument to the block.
That means the first time the block is executed, val1 will be equal to 1, and val2, val3, etc. will be nil because only one value is being passed to the block. The second time the block is executed, val1 will be equal to 2. val2, val3, etc. will be nil every time.
If you want to extract the elements of the array into variables, you don't need a loop. All you need to do is this:
val1, val2, val3, val4, val5 = array
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics #{val5}"
That's probably not necessary, though, since you can refer to the array elements directly in your string interpolation (#{...}):
puts "#{array[0]} topic is #{array[1]}, #{array[2]} topic is #{array[3]}, All topics #{array[4]}"
Here's a way that allows the elements of array to be different types of objects, and for array to have a variable length (defined in a particular, suggestive way).
Code
def fmt(array)
(array[0..-2].each_slice(2)
.map { |e| e.join(' topic is ') } \
<< "all topics #{array.last}").join(', ')
end
Examples
fmt [1,2,3,4,5,6,7]
#=> "1 topic is 2, 3 topic is 4, 5 topic is 6, all topics 7"
fmt [2.1,3,"hi","ho",:a]
#=> "2.1 topic is 3, hi topic is ho, all topics a"
array = ["First", "loops", "second", "methods", "third", "metaprogramming",
"are important for you to understand"]
fmt(array)
#=> "First topic is loops, second topic is methods, third topic is " +
# "metaprogramming, all topics are important for you to understand"
Here's a way that allows the elements of array to be different kinds of objects and for array to have a variable length (defined in a particular, suggestive way).
Code
def fmt(array)
(array[0..-2].each_slice(2)
.map { |e| e.join(' topic is ') }
.push "all topics #{array.last}")
.join(', ')
end
Examples
fmt([1,2,3,4,5,6,7])
#=> "1 topic is 2, 3 topic is 4, 5 topic is 6, all topics 7"
fmt([1,2.5,"cat","dog",:symbol])
#=> "1 topic is 2.5, cat topic is dog, all topics symbol"
array = ["First", "loops", "second", "methods", "third", "metaprogramming",
"are important for you to understand"]
fmt(array)
#=> "First topic is loops, second topic is methods, third topic is " +
# "metaprogramming, all topics are important for you to understand"