Find previous element in Ruby array Enumerable Enumerator

时间:2017-08-30 20:24:15

标签: ruby

I have an array public void startWorkflowTwo() { Intent intent = new Intent(MainActivity.this, LeaveWorkflowActivity.class); startActivity(intent); }

If I have an element in the array, I can find the next element in the array via the public void startWorkflowCompleted() { Intent intent = new Intent(MainActivity.this, WorkflowCompletedActivity.class); startActivity(intent); finishAffinity(); }

Is there a method that I can use to find the previous element SplashActivity -> MainActivity -> LeaveWorkflowActivity or a = [1, 2, 3, 4, 5] such that the result is

a[0].next

I Googled around a bit and it seems as if most other similar questions involve a loop which I don't want to do. I also checked out the Ruby docs of Enumerator & Enumerable and couldn't seem to find one.

a[1].previous

Thanks in advance!

3 个答案:

答案 0 :(得分:6)

If you have an array:

<Footer>

Then calling Home will return the object About, and there's nothing special about that value, it's without context once you've retrieved it. As such, calling a = [ 1, 2, 3, 4 ] on it will always yield a[1] because that's what Integer#next does.

In order to navigate through that array you need an iterator of some sort, like Enumerator:

2

Now you can do what you want:

next

Note that this interface isn't as flexible as you're expecting. You can call 3 to advance, or e = a.each to go back to the beginning, but there's no e.next # => 1 e.next # => 2 . Ruby doesn't have what other languages term as bi-directional iterators, but you might be able to extend this class to add the functions you need if you're feeling brave.

答案 1 :(得分:0)

我总是最终会鞭打这样的东西。

这种方法当然不限于Array-我不想将其设为EnumerableScanner,但是,由于某些枚举保持复杂状态(例如斐波那契数列) )。

class ArrayScanner
  attr_reader :index, :array

  def initialize(array)
    @array = array
    @index = 0
  end

  def next
    raise StopIteration unless next?
    @array[@index += 1]
  end

  def peek
    raise StopIteration unless next?
    @array[@index + 1]
  end

  def next?
    @index + 1 != @array.size
  end

  def prev
    raise StopIteration unless prev?
    @array[@index -= 1]
  end

  def peek_prev
    raise StopIteration unless prev?
    @array[@index - 1]
  end

  def prev?
    @index - 1 >= 0
  end

  def eof?
    !next?
  end

  def bof?
    !prev?
  end

  def current
    @array[@index]
  end

  def current=(new_value)
    @array[@index] = new_value
  end

  def size
    @array.size
  end

  def pos
    @index
  end

  def rewind
    @index = 0
  end
end

a = ArrayScanner.new [1, 2, 3, 4, 5]
a.current #=> 1
a.next    #=> 2
a.current #=> 2
a.prev    #=> 1
a.prev?   #=> false
a.bof?    #=> true
4.times { a.next }
a.eof?    #=> true
a.current #=> 5

crystal language具有类似的方法,它具有Iterator模块。

答案 2 :(得分:-1)

a = [1, 2, 3, 4, 5]

i = 0
a[i]      #=> 1
a[i.next] #=> 2
a[i.pred] #=> 5

i = 1
s = 1
a[i]      #=> 2
a[i + s]  #=> 3
a[i - s]  #=> 1