Ayman Salah
Ayman Salah

Reputation: 1089

Function call in Ruby

I am new to ruby and I want to achieve this:

Foo.runtask param1: :asd, param2: :qwerty

I know how to create a function taking two parameters, but I want to know how to call it like I mentioned specifically "param1:" and "param2:"

Upvotes: 0

Views: 57

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84182

From ruby 2.0 onwards ruby supports named arguments, so while you can still declare your method as just taking a single options argument you can also do

def foo(param1: 1, param2: :bar)
  ...
end

Deep down in the inside there is still a hash of arguments being passed around, but this allows you to specify default values easily (like normal default values these can be any ruby expression) and will raise an exception if you pass a names parameter other than a listed one.

In ruby 2.1 you can also have mandatory named arguments

def foo(param1: 1, param2:)
  ...
end

param2 is now mandatory.

In both cases you invoke the method like before:

foo(param1: :asd, param2: :qwerty)

In fact just by looking at this invocation you can't tell whether these will be consumed as named arguments or as a hash

You can of course emulate this with hashes but you end up having to write a bunch of boilerplate argument validation code repeatedly.

To tell whether a parameter is taking its default value was passed explicitly you can use this well known trick

def foo(param1: (param_1_missing=true; "foo")
  ...
end

Here param1 will be set to "foo" by default and param_1_missing will be true or nil

Upvotes: 2

Santhosh
Santhosh

Reputation: 29174

param1: :asd, param2: :qwerty It is a shorthand for { param1: :asd, param2: :qwerty }, which is a Hash (In some cases, you can omit the curlies of a Hash).

If you want to pass arguments like that, you method should accept a Hash as the parameter

eg

def my_method(options)
  puts options[:param1]
  puts options[:param2]
end

Then you can call my_method param1: :asd, param2: :qwerty

Upvotes: 3

Related Questions