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
tap quite a few times and wanted to find out more :-)tap is the new fad nowadays.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.
like some other array element and return element if there are no similar elements. Like: [ {title:'h1',value:'ttt'}, {title:'h2',value:'h2'}, {title:'h1',category:5,value:'needs to be returned instead instead of first one} ] What is the better way to do this?