Ruby Parameter Counting Rules

What are the Ruby rules regarding the number of parameters for various functionally similar constructs and what are they called?

eg. I noticed that when blocks with several parameters pass one parameter of an array, it expands, and this does not seem to apply to methods. I often see this with the methods of the Enumerable module for a Hash object.

{a: 5}.map{|x| x} # [[:a, 5]]
{a: 5}.map{|k, v| [k, v]} # [[:a, 5]]
[[:a, 5]].map{|x| x} # [[:a, 5]]
[[:a, 5]].map{|k, v| [k, v]} # [[:a, 5]] 

proc1 = Proc.new{|x| x}
proc1.call 5 # 5
proc1.call 5, 6 # 5
proc1.call [5, 6] # [5, 6]

proc2 = Proc.new{|k, v| [k, v]}
proc2.call 5 # [5, nil]
proc2.call 5, 6 # [5, 6]
proc2.call [5, 6] # [5, 6], not [[5, 6], nil]

def f(k, v); [k, v] end
f 5 # ArgumentError
f 5, 6 # [5, 6]
f [5, 6] # ArgumentError

def g(*vargs); vargs end
g 5 # [5]
g 5, 6 # [5, 6]
g [5, 6] # [[5, 6]]

However, the documentation for Proc.call does not seem to mention this.

Then there are also lambda that are slightly different, methods like Proc using &:name, and maybe some others. And I'm not quite sure what Proc.new{|x| x}.callexactly is the same as yieldin method_that_takes_a_block{|x| x}.

+4
2

-splat

proc2 ( ):

proc2 = Proc.new{|k, v| [k, v]}
proc2.call 5 # [5, nil]
proc2.call 5, 6 # [5, 6]
proc2.call [5, 6] # [5, 6], not [[5, 6], nil]
proc2.call [5, 6, 7] # [5, 6]

ruby ​​ :

k, v= 5 # => k=5, v=nil
k, v= 5, 6 # => k=5, v=6
k, v= 5, 6, 7 # => k=5, v=6, 7 is not assigned

splat:

k, v= *[5, 6] # => k=5, v=6

splat:

k, *v= *[5, 6, 7] # => k=5, v=[6, 7]

ruby ​​ :

k, v= [5, 6] # => k=5, v=6
k, v= [5, 6, 7] # => k=5, v=6, 7 is not assigned

, auto-splat Proc

+7

, 1.9.

Ruby 1.9 . ,

{|a, b, c|}

-

yield foo, bar, baz

a, b, c, = foo, bar, baz

"", . , initialize:

define_method(:initialize) do |@foo, @bar| end

, , ! ! , , , ,

Foo.new(23, 42)

@foo, @bar = 23, 42

- : setter !

{|foo.bar, baz.quux|}

, yield - , foo.bar= baz.quux=.

"" Ruby 1.9+. , , setter . , Ruby : - Hash#each.

, , . , , , . ( , , API, !) .

Proc , lambdas . ( return, BTW: Proc s, return , lambdas .) : Proc, - .

0

All Articles