开发者

loops within ruby

Doing a very simple loop to display various data,

for _test in @test ...

I want to be able to,

1) get the first value _test.name.first()???

2) get the previous value(meaning, the last iteration, so I i iterated the first time, I want to grab it again, when its in the second loop

Thank you

--- update

What I mean is this

  1. Doug, 2. Paul 3.Steve

So when I have Paul as the current name, I want to be able to get the last iteration (Doug) and same with Steve (get Paul)....So like an array, get th开发者_C百科e last, first but in this case the previous value


  1. I'm not sure what you mean here. @test.first will give you fir first item in the collection. Otherwise, what do you mean by the "first value" of the _test object?

  2. each_cons may help you here: it iterates over an array giving you consecutive sub-arrays. An example: [:a, :b, :c, :d].each_cons(2).to_a results in [[:a, :b], [:b, :c], [:c, :d]]


Here's a hacky but straightforward way to do it:

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

Output:

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


You'd better clarify your question, it's pretty confusing this way.

I don't understand 1), so I'll try to address 2), at least the way I understood it.

There's a method Enumerable#each_cons, I think it's there from Ruby 1.8.7 onwards, which takes more than one element with each iteration:

(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

So, effectively, you'll get the previous (or next, depending on how you see it) value on each iteration.

In order to check whether you are in the first iteration, you can use #with_index:

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

And you can combine both from the above in the same loop.


You can knock something up like that with 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

This should output something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜