【问题标题】:undefined local variables or method for main: Object <NameError> For Rubymain 的未定义局部变量或方法:Object <NameError> For Ruby
【发布时间】:2016-10-04 09:08:03
【问题描述】:

我收到一条错误消息,上面写着 rb:10:in 'activities': undefined local variable or method 'beach_bum' for main:Object

我通过输入活动来调用方法/函数,我不确定我在这里缺少什么?我的代码在下面列出。

def activities
  puts " Hi, groupFish friends, you are in Beautiful San Diego Today."
  puts "Do you want to check out La Jolla Beach swipe left or check out Coachella swipe right?"
  puts "There are 25 things that are happening within 5 miles!"

  print ">"
  choice = $stdin.gets.chomp

  if choice == "left"
    beach_bum
  elsif choice == "right"
    coachella
  else
    puts "Keep on swiping and be sure use the search hashtag feature to find activities!"
  end
end

活动

def beach_bum
  puts " Tera and John are here watching the seals, care to join?"
  puts " Do you want to meet them? Y or N."
  choice= $stdin.gets.chomp

  if choice == "Y"
    puts "Great, we'll see you at the cove in 15 minutes."
    exit(0)
  elsif choice == "N"
    puts " Keep swiping, there's rock climbing nearby"
  else puts " Jamba Juice is having a free smoothie before 2pm, it's 2miles away"
  end
end


def coachella
  puts " Heck Yeah, you are about to enter one of the biggest concerts of all time"
  puts " There are a total of 10,000 party goers today"

end

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您在定义它之前使用了方法 beach_bum。 您只能在定义方法后使用它。 我知道在某些语言中这无关紧要,但在 Ruby 中确实如此。 您还可以通过事后重新定义来修改现有方法。

    def foo; 'bar' ; end
    foo # bar
    def foo; 'changed' ; end
    foo # changed
    

    将代码中方法的位置移到活动方法之前。

    【讨论】:

    • 非常感谢彼得。这行得通,我假设当我输入对我不起作用的coachella 时。一旦我切换它,它就起作用了!另外,我不确定我是否理解这个逻辑,为什么顺序很重要?我首先调用了活动函数,因此它会按该顺序运行。
    • 顺序很重要,因为 Ruby 无法穿越到未来。如果调用时该方法未定义(即甚至不存在),那么 Ruby 应该如何执行它不知道它是什么以及甚至不存在的东西?
    • @Jörg W Mittag Thnx Jörg,我在回答 Nathan 时说得更清楚,你能接受这个答案吗?以后发布代码时,请使用{}按钮正确格式化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2020-06-02
    • 2016-02-14
    相关资源
    最近更新 更多