基本的Ruby/Rails语法

use*_*453 4 ruby ruby-on-rails

我熟悉Java和C,并且相当熟悉Ruby,但有时会被一些Ruby语法搞糊涂.

例如,以下行应该是什么?我假设我们正在进行函数调用protect_from_forgery()
但是这是什么意思with: :exception?我猜:exception是哈希值(例如{ :exception => "NullPtr" }),但是什么with:呢?

protect_from_forgery with: :exception
Run Code Online (Sandbox Code Playgroud)

Pet*_*ete 8

那条线上发生了很多语法糖.我认为绊倒你的是哈希和符号的简写.如果您不熟悉符号,请参阅此处以获得一个好的教程.

删除所有语法糖后,该行可写为:

protect_from_forgery({:with => :exception})
Run Code Online (Sandbox Code Playgroud)

打破它,发送到方法的最后一个参数被视为哈希,即使没有花括号.所以:

protect_from_forgery({:with => :exception})
Run Code Online (Sandbox Code Playgroud)

是相同的:

protect_from_forgery(:with => :exception)
Run Code Online (Sandbox Code Playgroud)

当散列的键是符号时,可以通过将冒号放在单词的末尾而不是开头来定义散列和键.例如

protect_from_forgery(:with => :exception)
Run Code Online (Sandbox Code Playgroud)

是相同的:

protect_from_forgery(with: :exception)
Run Code Online (Sandbox Code Playgroud)

最后,方法参数周围的括号在Ruby中是可选的.所以:

protect_from_forgery(with: :exception)
Run Code Online (Sandbox Code Playgroud)

是相同的:

protect_from_forgery with: :exception
Run Code Online (Sandbox Code Playgroud)