在红宝石中循环

时间:2010-08-13 15:43:33

标签: ruby-on-rails ruby

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

@test中的_test ...

我希望能够,

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

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

谢谢

---更新

我的意思是这个

  1. Doug,2。Paul 3.Steve
  2. 因此,当我将Paul作为当前名称时,我希望能够获得最后一次迭代(Doug)并与Steve相同(得到保罗)....所以就像一个数组,得到最后一个,第一个但是在这种情况是前一个值

4 个答案:

答案 0 :(得分:3)

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

  2. each_cons可以帮到你:它迭代一个数组,为你提供连续的子数组。例如:[:a, :b, :c, :d].each_cons(2).to_a会产生[[:a, :b], [:b, :c], [:c, :d]]

答案 1 :(得分:2)

这是一种简单易行的方法:

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

答案 2 :(得分:1)

你最好澄清你的问题,这种方式很混乱。

我不明白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

你可以在同一个循环中将上述两者结合起来。

答案 3 :(得分:0)

你可以通过注射来解决这个问题:

# 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