arthurnum
arthurnum

Reputation: 68

ruby, two ways how to pass params to proc

I looked through this code and found author passes params to block using []. I tryed it myself

my_proc = proc { |x| x + 1 }
a = 0
my_proc[a]        # => 1
my_proc.call(a)   # => 1

What is the difference between this two calls? Is this a syntax sugar?

Upvotes: 0

Views: 58

Answers (2)

Holger Just
Holger Just

Reputation: 55768

Both ways are exactly the same and are aliases to each other. Thus, both variants call the same method which is not determined by any special syntax. It is basically defined as:

class Proc
  def call(*args)
    #...
  end

  alias [] call
end

You might be interested to note that there is even a third way:

my_proc.(a)

This is actually syntactic sugar (i.e. is an extension of the syntax of the Ruby language language). All objects accepting #call can be "called" that way and Ruby ensures to invoke the call method.

Upvotes: 1

Jimmy
Jimmy

Reputation: 37081

They are functionally identical. You can use whichever style you prefer.

Upvotes: 1

Related Questions