我有一个数组(外部数组),包含三个数组(内部数组),每个数组有三个元素.
array = [[a, b, c], [d, e, f], [g, h, i]]
Run Code Online (Sandbox Code Playgroud)
我想使用外部数组的索引选择特定的内部数组,然后根据其索引选择所选内部数组中的值.这是我尝试过的:
array.each_index{|i| puts "letter: #{array[i[3]]} " }
Run Code Online (Sandbox Code Playgroud)
我希望能给我以下输出
letter: c letter: f letter: i
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了
letter: [[a, b, c], [d, e, f], [g, h, i]]
Run Code Online (Sandbox Code Playgroud)
我也试过了
array.each_index{|i| puts "letter: #{array[i][3]} " }
Run Code Online (Sandbox Code Playgroud)
但我得到了相同的结果.请任何建议非常感谢.我需要一个简单的解释.
我有一个带有if elsif语句的for循环.在第一个if,如果满足条件,我希望它停在那里并继续循环的下一次迭代.
这是我想要做的非常简化的版本:
array = [1,2,3,4,"x"]
for i in 0..(array.count -1)
if array[i] == "x"
#start next for loop iteration without executing the elsif
elsif array[i] < 3
puts "YAY!"
end
end
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的是迭代一个数组,其中除了一个元素之外的所有元素都是整数,但其中一个是一个字符串.在字符串元素上,我需要循环(无论哪种类型最好)跳过其余代码并转到循环的下一次迭代.这很重要,因为第二个if语句使用'array_element <11条件',所以如果它在字符串元素上运行,我得到"String与11的比较失败"
所以我想要arr [x] [3]这就是我尝试的但它给了我8 8 8 8而不是一个8.
arr = [[1,2,3,"4"], [5,6,7,8], [9,10,11,12]]
arr.each{|x|
x.each {|i|
next if x[3].instance_of? String
if x[3] < 12 puts x[3]
end
}
}
Run Code Online (Sandbox Code Playgroud)
好的,这有效!! 谢谢你iAmRubuuu !!
arr = [1,2,3,"4"], [5,6,7,8], [9,10,11,12], [13,14,15,"16"], [17,18,19,20]]
arr.each_with_index{|x, i|
next if x.last.instance_of? String
if x.last < …Run Code Online (Sandbox Code Playgroud)