Arguments and Parentheses
This lesson discusses the use of parentheses when passing arguments to the methods.
If you have read carefully, you may have noticed that we said about the code
puts 5
that puts
is a method call. And then later we’ve enclosed the value
3
in parentheses when calling the method: add_two(3)
.
That’s right:
💡 In Ruby, when you define or call (execute, use) a method, you can omit the parentheses.
So these lines mean exactly the same:
Press + to interact
puts "Hello!"puts("Hello!")
And so do these:
Press + to interact
puts add_two 2puts add_two(2)
And all of these:
Press + to interact
puts add_two 2puts add_two(2)puts(add_two 2)puts(add_two(2))
When do you use parentheses, and when do you omit them?
There is no clear rule about this, but there are some conventions. For now, you can just stick with the convention we are using at our study groups, which is:
- Use parentheses for all method calls that take arguments, except for the methods
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy