1

I need an array of blocks, where each block can take an argument:

array = [
  block do |x| puts x end,
  block do |x| puts x.to_s+" - " end
]

and make a request in the form of:

array[0] << 34

I had an idea to convert large numbers into words. I was wondering about the limits of blocks. There may be another way of doing it, but I am curious if this is possible.

2
  • 1
    What exactly do you want to achieve? Commented Mar 7, 2014 at 18:30
  • 1
    I don't understand a word of what you are willing to do concretly. Commented Mar 7, 2014 at 18:32

3 Answers 3

7

While you're getting answers that tell you what is possible with Ruby procs and lambdas, I think it's important to understand that blocks are not objects in Ruby and cannot be included in arrays or otherwise manipulated as Ruby objects. They only come into existence in conjunction with a method call.

I'd like to be able to point you to some official/complete documentation on the subject of blocks, procs and lambdas, but while there's a lot of stuff out there, most of it has some subtle but important flaws imho. However, if you google for Ruby blocks, procs and lambdas, you'll get something that is at least 90% accurate.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Good point. As a result of your answer, I changed all instances of "block" in my answer to "proc", since that is technically what they are.
5

You can use lambdas:

array = [ lambda { |x| puts x }, lambda { |x| puts "#{x} - " } ]

array[0].call(34) # prints 34

If you need to use the << operator to invoke the Proc, then you can create a class and overload it:

class Foo
    def initialize( &proc )
        @proc = proc
    end
    def <<( input )
        @proc.call( input )
    end
end

array = [
    Foo.new { |x| puts x },
    Foo.new { |x| puts "#{x} - " } ]

array[0] << 34 # prints 34

2 Comments

I start to like ruby :) Thank you that was simpler then i thought !
use of << was a wild guess .... :) dam i did not think of this , even though i knew about overriding functions :)
3

To run it through a specific lambda:

a = [
  ->(x) { puts x },
  ->(x) { puts "#{x} - " }
]

a[0].(34) # => prints 34

To run it through every block:

a.map { |b| b.(3) }

3 Comments

This looks less initiative for me but i will test is as well Thank you for your answer !
Well i actually want to run through items manually as i need to put some additional logic before, but it looks like it can come handy at some point :)
Updated my answer with an alternate syntax :)

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.