Ruby中变量前的感叹号 [英] Exclamation points before a variable in Ruby
问题描述
浏览ruby僧侣,偶尔他们用不熟悉的语法从左侧字段中抛出一个代码:
going through ruby monk and once in a while they throw out a code from the left field with unfamiliar syntaxes:
def compute(xyz)
return nil unless xyz
xyz.map {|a,b| !b.nil? ? a + b : a}
end
有人可以解释这三种用法吗?
1)对象
之前的惊叹号2)附加问号3)lambda中的冒号用法
Can somebody explain these three uses? 1) The exclamation before the object 2) The additional question mark 3) The colon usage within the lambda
推荐答案
!
只是一个not运算符。
!
is a just a not operator.
b.nil?
是一种检查b的值是否为nil的方法。返回布尔值。
b.nil?
is a method that checks the value for b is nil or not. Returns a boolean.
!b.nil? ? a + b:a
是一个三元操作,是操作。它的工作方式如下:
!b.nil? ? a + b : a
is a ternary operation is action. It works like this :
if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this
相当于说
if a then b else c end
所以与以上语句是否!b.nil?
是 true
答案是 a + b
否则为 a
。
So relating with above statement if !b.nil?
is true
answer is a+b
else it is a
.
了解更多此处
这篇关于Ruby中变量前的感叹号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!