質問

How can I access the array from within block in Ruby?

For example:

[1,2,3].each{|e| puts THEWHOLEARRAY.inspect }

Where THEWHOLEARRAY should return [1,2,3].

役に立ちましたか?

解決

What you are seeking is either tap, already implemented:

[1, 2, 3].tap { |ary|
  puts ary.inspect
  ary.each { |e|
    # ...
  }
  'hello' ' ' + 'world' # return value demo
} # returns the original array

Or ergo method, coming soon:

class Object; def ergo; yield self end end # gotta define it manually as of Ruby 2.0.0
[1, 2, 3].ergo { |ary|
  puts ary.inspect
  ary.each { |e|
    # ...
  }
  'hello' ' ' + 'world' # return value demo
} # returns the block return value

他のヒント

It's not exactly clear what you want to do. Do you mean something like this?:

THEWHOLEARRAY = [1,2,3]
THEWHOLEAREAY.each{ |e|
  puts THEWHOLEARRAY.inspect
}

Ruby lets you access variables outside a block. Typically it would be another variable, not the one you are iterating over though.

You cannot. The block variable only holds information about a single element for each iteration. It does not have information of the whole array. Furthermore, each will iterate as many times as the number of the elements in the array. Do you want to inspect that many times? It does not make sense.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top