Robert
Robert

Reputation: 311

Why does the new method use a parenthesis for its argument whereas the render method doesn't?

I have been studying Rails for a while and I don't understand when to use a parenthesis for a method since there seems to be no consistency in my eyes.

def create
   post.new(post_params)
 if @post.save
   redirect_to root_path
 else
   render 'new'
end

end

Upvotes: 1

Views: 208

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

You're right, there's no consistency.

def create
  post.new(post_params)
  if @post.save
    redirect_to root_path
  else
    render 'new'
  end
end

could also be written:

def create()
  post.new post_params
  if @post.save()
    redirect_to(root_path)
  else
    render('new')
  end
end

Both methods would work exactly the same.

There are style guidelines, though.

Always omit parentheses for method calls with no arguments.

Always omit parentheses for methods that are part of an internal DSL (e.g., Rake, Rails, RSpec).

Use def with parentheses when there are parameters. Omit the parentheses when the method doesn't accept any parameters.

Use parentheses around the arguments of method invocations

The first method seems to apply those guidelines, the second one doesn't.

Upvotes: 2

perrukozsh
perrukozsh

Reputation: 44

Because all in ruby and ruby on rails it is object.

example

class People
  def info(name, age, color)
    puts name
    puts age
    puts color
  end
end
people = People.new
people.info("Juanito", "34", "Blue")

Upvotes: 0

Related Questions