Ruby on rails 为什么新方法使用括号作为参数,而render方法不使用';T
我研究Rails已经有一段时间了,我不知道什么时候应该使用括号作为方法,因为在我看来似乎没有一致性Ruby on rails 为什么新方法使用括号作为参数,而render方法不使用';T,ruby-on-rails,ruby,Ruby On Rails,Ruby,我研究Rails已经有一段时间了,我不知道什么时候应该使用括号作为方法,因为在我看来似乎没有一致性 def create post.new(post_params) if @post.save redirect_to root_path else render 'new' end 结束因为在ruby和RubyonRails中,它都是对象 范例 class People def info(name, age, color) puts name puts
def create
post.new(post_params)
if @post.save
redirect_to root_path
else
render 'new'
end
结束因为在ruby和RubyonRails中,它都是对象 范例
class People
def info(name, age, color)
puts name
puts age
puts color
end
end
people = People.new
people.info("Juanito", "34", "Blue")
你说得对,没有一致性
def create
post.new(post_params)
if @post.save
redirect_to root_path
else
render 'new'
end
end
也可以写成:
def create()
post.new post_params
if @post.save()
redirect_to(root_path)
else
render('new')
end
end
两种方法的工作原理完全相同
不过也有
对于没有参数的方法调用,始终忽略括号
对于属于内部DSL一部分的方法(例如Rake、Rails、RSpec),请始终省略括号
如果有参数,请使用带括号的def。当方法不接受任何参数时,省略括号
在方法调用的参数周围使用括号
第一个方法似乎适用于这些准则,第二个则不适用。我在某个地方读到,当方法的第一个参数是散列括号是可选的时,有关详细信息,请参阅。@ImranAli,与方法的第一个参数无关。在某些情况下,使用哪一个会有差异(主要是当涉及括号或块时),但在OP中,唯一的差异是风格上的差异
post.new post_参数
和重定向到(根路径)
也同样有效。