你如何在Ruby中编写一个代码片段,以相反的顺序打印出1到200之间3的每个倍数?
这是我到目前为止的代码:
(1..200).each do | i | ##loop it then
if i % 3 == 0
答案 0 :(得分:4)
您可能需要#select
和#reverse
。
puts (1..200).select { |i| i % 3 == 0 }.reverse
答案 1 :(得分:4)
将三的倍数从200打印到1的最简单方法是使用Integer#downto
:
200.downto(1) do |i|
puts i if i % 3 == 0
end
与其他答案不同,它不需要将范围转换为数组或创建和数组并将其反转。
答案 2 :(得分:0)
您可以尝试将值分配给变量a,然后您可以:
a.reverse!
puts a
这也可以作为一个例子:
def reverse_string(string) # method reverse_string with parameter 'string'
loop = string.length # int loop is equal to the string's length
word = '' # this is what we will use to output the reversed word
while loop > 0 # while loop is greater than 0, subtract loop by 1 and add the string's index of loop to 'word'
loop -= 1 # subtract 1 from loop
word += string[loop] # add the index with the int loop to word
end # end while loop
return word # return the reversed word
end # end the method
答案 3 :(得分:0)
#reverse
没有#to_a
方法,但您可以调用#reverse_each
返回这些数字的数组,然后在该数组上调用(1..200).to_a.reverse_each { |i| puts i if i % 3 == 0 }
以相反的顺序迭代数字:
encodeURIcomponent
答案 4 :(得分:0)
这有效:
reverse_each
在这里你要指定1到200之间的数字范围,将它们转换为数组,反转顺序并遍历每个元素以查看它是否可以被3整除(即如果你将它除去3,它不应该有余数),如果是这样,打印数字:)
编辑:乔丹指出,写作 reverse.each
而不是
using Interpolations
A_grid = [1 2; 3 4]
A = interpolate((0:1, 0:1), A_grid, Gridded(Linear()))
a = A[0.5, 0.5]
println(a)
效率更高。
答案 5 :(得分:0)
OP希望打印范围的某些元素。首先构造一个数组是低效的(但当然不是必须的)。我的答案和其他一些人没有创建数组。
假设范围的格式为first..last
。要以相反的顺序打印每个multiple
元素,您可以写:
def rev_n_skip(first, last, multiple)
(first..last).step(multiple).reverse_each { |i| print "#{i} " }
puts
end
rev_n_skip(1, 19, 3) #-> 19 16 13 10 7 4 1
rev_n_skip(1, 18, 3) #-> 16 13 10 7 4 1
rev_n_skip(1, 17, 3) #-> 16 13 10 7 4 1
rev_n_skip(1, 16, 3) #-> 16 13 10 7 4 1
rev_n_skip(1, 15, 3) #-> 13 10 7 4 1
rev_n_skip(2, 19, 3) #-> 17 14 11 8 5 2
rev_n_skip(2, 18, 3) #-> 17 14 11 8 5 2
rev_n_skip(2, 17, 3) #-> 17 14 11 8 5 2
rev_n_skip(2, 16, 3) #-> 14 11 8 5 2
rev_n_skip(2, 15, 3) #-> 14 11 8 5 2
答案 6 :(得分:0)
不需要数组的其他三种方式是:
(1..200).reverse_each { |i| puts i if i % 3 == 0 }
或者:
(200..1).step(-1).each { |i| puts i if i % 3 == 0 }
并且:
200.step(1, -1).each { |i| puts i if i % 3 == 0 }