ruby返回undefined方法+为nil:nilClass

时间:2014-09-25 16:07:57

标签: ruby

运行以下代码:

# experiment
time = 5000
# when time reaches 10000, I'm off duty
def speedup_time(incre)
  time += incre
  yield(time)
end

puts "is the day over yet? #{speedup_time(2000){
  if incre >= 10000
    "yes: #{time}"
  else
    "no: #{time}"
  end
}}"

我遇到了这个错误:undefined method "+" for nil:nilClass

2 个答案:

答案 0 :(得分:2)

范围之外的

time变量(Ruby中的define方法具有自己的范围,并且无法在外部看到任何变量)。试试这个:

# when time reaches 10000, I'm off duty
def speedup_time(incre)
  time = 5000
  time += incre
  yield(time)
end

你的第二个表达错了。我认为应该是这样的:

speed_var = speedup_time(2000) do |time|
  if time >= 10000
    "yes: #{time}"
  else
    "no: #{time}"
  end
end
puts "is the day over yet? #{speed_var}"

或者使用三元运算符:

speed_var = speedup_time(2000) { |time| (time >= 10000) ? "yes: #{time}" : "no: #{time}" }
puts "is the day over yet? #{speed_var}"

或:

puts %Q|is the day over yet? #{speedup_time(2000){ |time| (time >= 10000) ? "yes: #{time}" : "no: #{time}"}}|

答案 1 :(得分:2)

  

我正在考虑使用收益率并将其调整为一个承诺。然后   我习惯于javascript中的风格,有没有办法适应   这与收益率。

你将不得不多学习一下,因为这也不会有效:

def do_stuff(x)
  yield
end


do_stuff(10) { puts x }


--output:--
2.rb:6:in `block in <main>': undefined local variable or method `x' for main:Object (NameError)
    from 2.rb:2:in `do_stuff'
    from 2.rb:6:in `<main>'

很明显,当涉及到ruby中的范围时,你会迷失方向。获得一本开头的红宝石书。阅读。 Ruby不是javascript。

#----A def creates a new scope--+
def do_stuff               #    |
  x = 10                   #    |
end                        #    |
#-------------------------------+
#...which means nothing inside that box can see anything outside the box
#except for constants, which are visible everywhere

y = 20

p = Proc.new do  #Proc.new and lambda create anonymous functions in ruby
  puts y
  puts x
  puts z
end

def test(p) 
  z = 30
  p.call #execute proc, can also be written as p[]
end

test p 

使用该示例,评论各种put语句。