繁体   English   中英

红宝石内部循环

[英]loops within ruby

做一个非常简单的循环来显示各种数据,

用于@test中的_test ...

我希望能够

1)获取第一个值_test.name.first()???

2)获取先前的值(意思是最后一次迭代,所以我第一次迭代,当它在第二个循环中时,我想再次抓住它

谢谢

-更新

我的意思是这个

  1. 道格2.保罗3.史蒂夫

因此,当我使用Paul作为当前名称时,我希望能够获得最后一次迭代(Doug),与Steve相同(获得Paul)。...就像数组一样,首先获得最后一个,但在这种情况下先前值

  1. 我不确定你在这里是什么意思。 @test.first将为您提供集合中的第一项。 否则, _test对象的“第一个值”是什么意思?

  2. each_cons可能在这里为您提供帮助:遍历一个数组,为您提供连续的子数组。 例如: [:a, :b, :c, :d].each_cons(2).to_a产生[[:a, :b], [:b, :c], [:c, :d]]

这是一种简单但简单的方法:

prev = nil
first = nil
(1..10).each do |i|
    if !prev.nil? then
        puts "#{first} .. #{prev} .. #{i}"
        prev = i
    elsif !first.nil? then
        puts "#{first} .. #{i}"
        prev = i
    else
        puts i
        first = i
    end
end

输出:

1
1 .. 2
1 .. 2 .. 3
1 .. 3 .. 4
1 .. 4 .. 5
1 .. 5 .. 6
1 .. 6 .. 7
1 .. 7 .. 8
1 .. 8 .. 9
1 .. 9 .. 10

您最好弄清楚您的问题,这种方式很令人困惑。

我不了解1),因此我将尝试解决2),至少是我理解的方式。

有一个方法Enumerable#each_cons ,我认为从Ruby 1.8.7开始就存在,每次迭代都需要多个元素:

(1..10).each_cons(2) do |i,j|
  puts "#{i}, #{j}"
end
1, 2
2, 3
3, 4
4, 5
5, 6
6, 7
7, 8
8, 9
9, 10
#=> nil

因此,有效地,您将在每次迭代中获得上一个(或下一个,具体取决于您如何看待)值。

为了检查您是否在第一次迭代中,可以使用#with_index

('a'..'f').each.with_index do |val, index|
  puts "first value is #{val}" if index == 0
end
#=>first value is a

而且,您可以将以上两者结合在一个循环中。

您可以使用inject来破坏类似的东西:

# passing nil to inject here to set the first value of last 
# when there is no initial value
[1,2,3,4,5,6].inject(nil) do |last, current| 
  # this is whatever operation you want to perform on the values
  puts "#{last.inspect}, #{current}"
  # end with 'current' in order to pass it as 'last' in the next iteration
  current
end

这应该输出类似:

nil, 1
1, 2
2, 3
3, 4
4, 5
5, 6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM