Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the different possibilities of passing parameters into ruby methods? param/hashlist/array/aproc?

Tags:

ruby

I am trying to understand Ruby in more depth and was reading:

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

However, I dont understand what the following means in that definition:

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

I know "param" is any number of parameters specified, and then i get lost what the remainder means?

For example, I have:

def doIt(param1, param2, param3)
end

and in this case [param]* is equal to param1, param2, param3...so where does hashlist come in? and *array and &aProc?

Could someone please clarify this for me

like image 946
Kamilski81 Avatar asked Nov 05 '22 07:11

Kamilski81


1 Answers

If the last argument of a 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 normal way:

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

Usually, the hash is defaulted to {} (def foo(x, y, the_hash = {})) so passing an empty hash fits to this scheme.

Additionally, you can specify one "catch-all" (splat) argument which will become an array of all arguments not already assigned to normal arguments:

def foo(p1, *rest)
  p rest
end

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

Or, e.g.

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

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

You cannot have splat arguments before arguments with default value. Therefore, the hash argument syntax and the splat argument are rarely used in combination.

Finally, in your method definition you can have as last argument an identifier prefixed with & which will point to the block at the method invocation (its Proc object) or be nil if there is none. This is normally not needed if you just want to invoke the block -- you can use yield for that.

def foo(&p)
   p.call
end

foo { puts "hello" } # hello

vs.

def foo
   yield
end

foo { puts "hello" } # hello
like image 54
undur_gongor Avatar answered Nov 15 '22 06:11

undur_gongor