ruby循环遍历数组和提取元素

时间:2014-08-28 18:20:03

标签: ruby arrays loops extract elements

这是我想要做的,但它不起作用。

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

6 个答案:

答案 0 :(得分:2)

array.each将为do中的每个元素执行一次块(endarray之间的部分),每次使用该元素作为第一个参数到街区。

这意味着第一次执行该块时,val1将等于1,而val2val3等将为nil因为只有一个值传递给块。第二次执行块时,val1将等于2val2val3等每次都会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"