1

I've recently started learning Ruby as a second programming language, having started with JavaScript a couple of months ago.

I've noticed in tutorials that what people refer to in Ruby as methods, often don't have the parenthesis() following the method like they do in Javascript.

Is it correct that all methods in JavaScript have parenthesis() and anything to the right of a dot without parenthesis is a property, but in Ruby a method can still be a method even without parenthesis?

I hope this question doesn't make me look like a complete idiot, but I don't want to trip myself up in the early stages so to speak.

2
  • TL;DR yes, methods in Ruby can be called without parenthesis, while in JavaScript you must have parenthesis when calling a method/function. Commented Nov 8, 2017 at 17:32
  • Possible duplicate of Do you leave parentheses in or out in Ruby? Commented Nov 8, 2017 at 18:38

1 Answer 1

1

Im ruby, methods are defined in the following way.

def hello_world
  puts "hello world!"
end

In javascript as you know is defined in this way:

function helloWorld(){
  console.log("hello world!")
}

In javascript, the ability to pass around functions as callbacks and the like is relatively easy.

In the above function, helloWorld and helloWorld() are two very disparate things. The first is a reference to a function where as the second is an actual invocation.

This circles back to ruby, where ruby doesn't have the concept of a function in the same way as javascript, it has methods. They have a similar concept as referenced functions in the way of procs and lambdas but the implementation is different.

All that to say this, ruby methods are called without parenthesis where as in JS they are

In ruby, parenthesis are optional

Sign up to request clarification or add additional context in comments.

2 Comments

Parentheses in ruby are not always optional. If the local variable with the same name exists in the current scope, parentheses are mandatory.
Also, one always might get a reference to the function with obj.method(:hello_world) which returns almost exactly the same thing (bound method) as helloWorld in your example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.