1

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].

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Amazing here is that during the day I saw this tap quite a few times and wanted to find out more :-)
@IlyaNovojilov: Functional programming and tap is the new fad nowadays.
1

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.

Comments

0

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.

1 Comment

Actually the task is to select elements of the array which are 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.