How To Use Arguments In Ruby
How Many Kind Of Arguments In Ruby?
We can answer: Three
- Required arguments
eg:
1 | def hello(name) |
In there, name is a required argument. it mean if you call hello method and do not pass an argument, the output that you see should like:
1 | hello() |
Let pass an argument and this error will gone.
1 | hello('Meo Meo') |
It’s very simple, I think we are make sence now.
- Default arguments
Almost like Required arguments. It has one more thing different:
That is when we pass argument in a method, we can set default value for it, and then when you call this method and unlucky forgot pass arguments for this method, your method still working, if it’s not received arguments when it is called, it will use the default value.
eg:
1 | def hello(name = "Meo Meo") |
- Optional arguments
Do you ever want to create a method and have no idea how many arguments does this method need?
Yes, we use optional arguments for this case, take a looke at the example below:
1 | def hello(*family) |
Keyword Arguments
It’s a new feature has come from ruby 2.0 to higher. It like pass arguments as a hash but more powerful.
eg:
1 | def hello(name: 'Chinh', age: 25) |
if you call hello method with no arguments:
1 | hello() |
It will use default value.
And then
If you pass argumets for it:
1 | hello('Chinh', 25) |
what will it return?
Error: yes, it will response an error, but why?
Because, with keyword arguments, you need to pass argumetns like a hash you declare when initial method. (same key).
1 | hello(name: 'Meo') |
If you want to required an argument with no default value, try this:
1 | def hello(name:, age:) |
It mean the method need to receive “a hash” with two key name and age. if it does not revieve, error will raise.