前/后递增/递减运算符(++和--)是非常标准的编程语言语法(至少对于过程语言和面向对象语言).
为什么Ruby不支持它们?我知道你可以用+=和完成同样的事情-=,但是排除这样的东西似乎有点奇怪,特别是因为它是如此简洁和传统.
例:
i = 0 #=> 0
i += 1 #=> 1
i #=> 1
i++ #=> expect 2, but as far as I can tell,
#=> irb ignores the second + and waits for a second number to add to i
Run Code Online (Sandbox Code Playgroud)
我理解Fixnum是不可改变的,但如果+=能够实现一个新的Fixnum并设置它,为什么不做同样的事情++呢?
包含=角色的作业的一致性是唯一的原因,还是我错过了什么?
在Java中,类似的东西i++会增加i1.
我怎么能用Ruby做?当然必须有比这更好的方法i = i + 1吗?
我在irb中获得了bizzare输出
>> [1, 2] + + [3]
NoMethodError: undefined method `+@' for [3]:Array
from (irb):2
from /home/marko/.rubies/ruby-2.3.1/bin/irb:11:in `<main>'
>> [1, 2] ++ [3]
NoMethodError: undefined method `+@' for [3]:Array
from (irb):3
from /home/marko/.rubies/ruby-2.3.1/bin/irb:11:in `<main>'
>>
Run Code Online (Sandbox Code Playgroud)
这是故意发生还是一个错误?
转换+ +成后面的逻辑是什么?+@
我正在做边缘小屋学习红宝石,而我却被贪婪的koan(182-183)卡住了一个神秘的错误.这里列出了规则
我知道我的代码是......令人印象深刻,我想我一旦我的逻辑声音(它可能不是)就重构它.
我感谢任何帮助.
def score(dice)
score = 0
if dice == []
return score
end
dice = dice.sort
dice = [1,1,4,5,6]
count = [0,0,0,0,0,0]
score = 0
dice.each do |face|
if face == 1
count[0]++
elsif face == 2 # this is line 45 with reported error
count[1]++
elsif face == 3
count[2]++
elsif face == 4
count[3]++
elsif face == 5
count[4]++
elsif face == 6
count[5]++
end
end
if count[0] >= 3
score+= 1000
count[0] = …Run Code Online (Sandbox Code Playgroud) 那么我可以在红宝石中实现这一点吗?4 ++
我最初的谷歌搜索显示我可以重新定义加号但是当我尝试定义++时它会对我产生错误.
test.rb:2: syntax error, unexpected '+', expecting ';' or '\n'
def ++()
^
test.rb:5: syntax error, unexpected keyword_end, expecting end-of-input
Run Code Online (Sandbox Code Playgroud) 使用Ruby,我似乎无法使用以下代码:
a = 1
a++
Run Code Online (Sandbox Code Playgroud)
irb当我从文件编译时,上面的行工作但不起作用.
我错过了什么吗?我正在使用Ruby 2.0.