我熟悉Java和C,并且相当熟悉Ruby,但有时会对某些Ruby语法感到困惑。
例如,以下行应该是什么?我假设我们正在进行函数调用protect_from_forgery()
?
但with: :exception
的含义是什么?我猜:exception
是一个哈希值(例如{ :exception => "NullPtr" }
)但是什么是with:
?
protect_from_forgery with: :exception
答案 0 :(得分:8)
该行中发生了很多语法糖。我认为绊倒你的是哈希和符号的简写。如果您不熟悉符号,see here for a good tutorial。
删除所有语法糖后,该行可写为:
protect_from_forgery({:with => :exception})
将其分解,即使没有花括号,发送给方法的最后一个参数也会被视为哈希。所以:
protect_from_forgery({:with => :exception})
与:
相同protect_from_forgery(:with => :exception)
当哈希的键是符号时,可以通过将冒号放在单词的末尾而不是开头来定义哈希和键。 E.g
protect_from_forgery(:with => :exception)
与:
相同protect_from_forgery(with: :exception)
最后,方法参数周围的括号在Ruby中是可选的。所以:
protect_from_forgery(with: :exception)
与:
相同protect_from_forgery with: :exception
答案 1 :(得分:0)
是protect_from_forgery
是一种采用optional hast argument
的方法
optional hast argument
此处with:
是一个内部为method
且:exception
为值的键,也是一种方法