What are the different options for passing parameters to ruby ​​methods? pairs / hashlist / array / approc?

I try to understand Ruby in more detail and read:

http://www.zenspider.com/Languages/Ruby/QuickRef.html#25

However, I do not understand what the following definition means:

parameters := ( [param]* [, hashlist] [*array] [&aProc] )

I know that "param" is any number of given parameters, and then I get lost, what does the remainder mean?

For example, I have:

def doIt(param1, param2, param3)
end

and in this case [param] * is equal to param1, param2, param3 ... so where is the hash list? and * array and & aProc?

Can someone clarify this for me.

+5
source share
1 answer

If the last argument to the method is a non-empty hash literal, you can pass it like this:

def foo(x, y, the_hash)
   p the_hash['key2']
end

foo(0, 0, :key1 => 'val1', 'key2' => 42)     # 42

instead of the usual way:

foo(0, 0, { :key1 => 'val1', 'key2' => 42 }) # 42

{} (def foo(x, y, the_hash = {})), .

, "catch-all" (splat), , :

def foo(p1, *rest)
  p rest
end

foo(0)          # "[]"
foo(0, 23, 42)  # "[23, 42]"

, ,

def foo(p1, *rest, p2)
  p rest
end

foo(0, 100)          # "[]"
foo(0, 100, 23, 42)  # "[100, 23]"

splat . - splat .

, &, ( Proc) be nil, . , - yield.

def foo(&p)
   p.call
end

foo { puts "hello" } # hello

.

def foo
   yield
end

foo { puts "hello" } # hello
+2

All Articles