这是我想要做的,但它不起作用。
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
答案 0 :(得分:2)
array.each
将为do
中的每个元素执行一次块(end
和array
之间的部分),每次使用该元素作为第一个参数到街区。
这意味着第一次执行该块时,val1
将等于1
,而val2
,val3
等将为nil
因为只有一个值传递给块。第二次执行块时,val1
将等于2
。 val2
,val3
等每次都会nil
。
如果要将数组元素提取到变量中,则不需要循环。您需要做的就是:
val1, val2, val3, val4, val5 = array
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics #{val5}"
但是,这可能没有必要,因为您可以直接在字符串插值(#{...}
)中引用数组元素:
puts "#{array[0]} topic is #{array[1]}, #{array[2]} topic is #{array[3]}, All topics #{array[4]}"
答案 1 :(得分:2)
您可以使用String#%
方法:
puts "%d topic is %d, %d topic is %d, All topics $%d" % array
答案 2 :(得分:0)
如果这是一个固定的元素和单词之间的数组,只需执行:
puts "#{array[0]} topic is #{array[1]}, #{array[3]} topic is #{array[4]}, All topics is #{array[5]}"
答案 3 :(得分:0)
array = [1,2,3,4,5]
val1, val2, val3, val4, val5 = array
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics #{val5}"
答案 4 :(得分:0)
这是一种允许array
的元素成为不同类型的对象,并且array
具有可变长度(以特定的,暗示性的方式定义)的方式。
<强>代码强>
def fmt(array)
(array[0..-2].each_slice(2)
.map { |e| e.join(' topic is ') } \
<< "all topics #{array.last}").join(', ')
end
<强>实施例强>
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"
答案 5 :(得分:0)
这是一种允许array
的元素是不同种类的对象,并且array
具有可变长度(以特定的,暗示性的方式定义)的方式。
<强>代码强>
def fmt(array)
(array[0..-2].each_slice(2)
.map { |e| e.join(' topic is ') }
.push "all topics #{array.last}")
.join(', ')
end
<强>实施例强>
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"