ruby “+=”(加等号)是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7638502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does "+=" (plus equals) mean?
提问by F F
I am doing some ruby exercises and it said I need to go back and rewrite the script with +=shorthand notations.
我正在做一些 ruby 练习,它说我需要回去用+=速记符号重写脚本。
This exercise deals primarily with learning new methods. The problem is, I have no idea what +=means when I tried to look it up online.
本练习主要涉及学习新方法。问题是,+=当我尝试在线查找时,我不知道是什么意思。
回答by Justin Niessner
+=is a shorthand operator.
+=是速记运算符。
someVar += otherVar
is the same as
是相同的
someVar = someVar + otherVar
回答by F F
Expressions with binary operatorsof the form:
具有以下形式的二元运算符的表达式:
x = x op y
Can be written as:
可以写成:
x op= y
For instance:
例如:
x += y # x = x + y
x /= y # x = x / y
x ||= y # x = x || y (but see disclaimer)
However, be warned that ||=and &&=can behave slightly ... different (most evident when used in conjunction with a hash indexer). Plenty of SO questions about this oddity though.
但是,请注意||=,&&=它的行为可能略有不同……(与散列索引器结合使用时最明显)。尽管如此,关于这种奇怪的问题有很多SO问题。
Happy coding.
快乐编码。
回答by chzbrgla
Not an ruby expert but I would think that it either appends to an existing String or increments an numeric variable?
不是 ruby 专家,但我认为它要么附加到现有的字符串,要么增加一个数字变量?
回答by Tilo
You should look for a good book about Ruby, e.g. http://pragprog.com/book/ruby3/programming-ruby-1-9
你应该找一本关于 Ruby 的好书,例如http://pragprog.com/book/ruby3/programming-ruby-1-9
The first 150 pages cover most of the basic things about Ruby.
前 150 页涵盖了有关 Ruby 的大部分基本内容。
str = "I want to learn Ruby"
i = 0
str.split.each do |word|
i += 1
end
puts "#{i} words in the sentence \"#{str}\""
=> 5 words in the sentence "I want to learn Ruby"

