在Ruby中,有些方法带有问号(?),会问include?询问是否包含有问题的对象,然后返回true/false。
但是为什么有些方法有感叹号(!)而其他方法没有呢?
这是什么意思?
在Ruby中,有些方法带有问号(?),会问include?询问是否包含有问题的对象,然后返回true/false。
但是为什么有些方法有感叹号(!)而其他方法没有呢?
这是什么意思?
当前回答
从themomorohoax.com:
刘海有以下几种用法,依我个人喜好而定。
如果活动记录方法没有这样做,则会引发错误 就像它说的那样。 活动记录方法保存记录或方法保存 对象(例如strip!) 方法做一些“额外的”事情,比如张贴到某个地方 一些行动。
关键是:只有在你真正想过是否要使用爆炸的时候 这是必要的,可以省去其他开发人员不得不这样做的烦恼 检查你为什么要使用爆炸声。
爆炸为其他开发者提供了两个线索。
方法调用后,没有必要保存对象 方法。 当你调用这个方法时,db会被改变。
其他回答
被称为“破坏性方法”,它们倾向于改变你所引用的对象的原始副本。
numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers # returns [nil,nil,nil,nil,nil]
通常,以!结尾的方法指示该方法将修改调用它的对象。Ruby将这些方法称为“危险方法”,因为它们更改了其他人可能引用的状态。下面是一个简单的字符串示例:
foo = "A STRING" # a string called foo
foo.downcase! # modifies foo itself
puts foo # prints modified foo
这将输出:
a string
在标准库中,您可以在很多地方看到名称相似的方法对,其中一个带有!一个没有。没有安全方法的方法被称为“安全方法”,它们返回原始方法的副本,其中对副本进行了更改,而被调用者没有更改。下面是没有使用!的相同示例:
foo = "A STRING" # a string called foo
bar = foo.downcase # doesn't modify foo; returns a modified string
puts foo # prints unchanged foo
puts bar # prints newly created bar
这个输出:
A STRING
a string
请记住,这只是一种约定,但许多Ruby类都遵循它。它还可以帮助您跟踪代码中修改的内容。
简单的解释:
foo = "BEST DAY EVER" #assign a string to variable foo.
=> foo.downcase #call method downcase, this is without any exclamation.
"best day ever" #returns the result in downcase, but no change in value of foo.
=> foo #call the variable foo now.
"BEST DAY EVER" #variable is unchanged.
=> foo.downcase! #call destructive version.
=> foo #call the variable foo now.
"best day ever" #variable has been mutated in place.
但是如果你曾经用downcase来调用一个方法!在上面的解释中,foo将永久地更改为downcase。downcase !不会返回一个新的字符串对象,而是在适当的位置替换字符串,完全将foo更改为downcase。 我建议你不要用小写!除非完全有必要。
底线:!方法只改变被调用对象的值,而没有!返回一个被操纵的值,而不重写调用该方法的对象。
只用!如果您不打算将原始值存储在调用方法的变量中。
我喜欢这样做:
foo = "word"
bar = foo.capitalize
puts bar
OR
foo = "word"
puts foo.capitalize
而不是
foo = "word"
foo.capitalize!
puts foo
以防万一我想再次访问原始值。
提醒一下,因为我自己也经历过。
在Ruby中,!改变对象并返回它。否则它将返回nil。
因此,如果你正在对一个数组进行某种操作,并调用方法.compact!没有东西要压缩,它会返回nil。
例子:
arr = [1, 2, 3, nil]
arr.compact!
=> [1, 2, 3]
Run again arr.compact!
=> nil
如果你需要在一行中使用数组arr,最好再次显式返回它,否则你将得到nil值。
例子:
arr = [1, 2, 3]
arr.compact! => nil
arr # to get the value of the array