【问题标题】:Ruby, Convert String Queries Into Method CallsRuby,将字符串查询转换为方法调用
【发布时间】:2013-05-31 09:09:08
【问题描述】:

只要用户输入方法名称,下面的代码就可以完全正常工作。我想避免要求用户在各种 get.chomp 提示中输入方法的名称。

我认为使用 case 语句将用户输入转换为方法调用会起作用,但我不断得到一个 .include? NoMethodDefined 错误。

class Foo

  def initialize(start_action)
    @start = start_action
  end

  def play
    next_action = @start
    while true
      case next_action.include?
      when beginning
        next_action = beginning
      when "instruct"
        next_action = instructions # returns instructions as
                                   # the method that's called below
      when "users"
        next_action = users # returns users as the
                            # method that's called below
      else 
        puts "Unknown command."
        next_action = # some placeholder method call that gets the user
                      # back to being able to make another choice
      end 
      puts "\n----------"
      next_action = method(next_action).call
  end

  def beginning
    puts "This is the beginning."
    next_action = gets.chomp
  end

  def instructions
    puts "These are the instructions"
    # code to display instructions omitted
    next_action = gets.chomp
  end

  def users
    puts "Here are your users"
    # code to display users omitted
    next_action = gets.chomp
  end

end

start = Foo.new(:beginning)
start.play

感谢任何建议或帮助。

【问题讨论】:

    标签: ruby string methods translate


    【解决方案1】:

    在第一次通过循环时,next_action 是符号 :beginning,而符号没有 include? 方法。

    此外,我认为您误解了 case 语句的工作原理 - 即使删除第一个错误,您的代码也会抱怨您将 0 个参数传递给 include?(而不是 1 个)

    我认为你的意思是

    case next_action
    when /instruct/
      ..
    when /users
       ..
    else
      ..
    end
    

    这将依次测试针对每个常规压制的下一步行动

    【讨论】:

    • 啊,是的。说得通。好的,所以,现在我已经按照您的建议进行了重构,并且不再收到 NoMethodError,但我似乎打破了 while 循环。而且它没有将“指导”或“用户”识别为有效选项。我得到的只是一个未知命令,然后在下一个提示中输入的任何内容都会退出该过程。我期待着被传回循环中。
    • 您当前的代码看起来不会调用开始方法
    • 我修复了 case 语句,将开头作为选项包括在内。它实际上是第一个被调用的方法,是吗?什么时候初始化 Foo?无论如何,即使我输入了其他选项之一,case 语句也无法识别它们。我得到的只是未知命令选项。我会在提示符下输入 [users](不带括号),case 语句认为这样不好。
    • 在您的代码中,case 语句正在执行开始并将 next_action 与该方法的返回值相匹配,而不是将 next_action 与文字“开始”相匹配
    • 好的。那么顺序是这样的:初始化类。 next_action = 开始。案例选择开始。通话开始。用户选择 = x。回来玩。无论用户选择什么,case 都选择 else 吗?为什么?
    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多