u=11=u 元编程 u=10=u

Ruby Metaprogramming "Depths"

我开始在 Ruby 学习元编程并且(我认为)我正在理解如何添加实例方法和变量,但前提是一次传入一个。例如,test.new_value = true。我想知道如何用两个点 test.like.this 为我的命令添加额外的深度。例如:

class Whosebug
  def initialize(name)
    @name = name
  end

  def method_missing(argument, *args)
    argument = argument.to_s

    if argument =~ /failing/
      puts 'FOUND FAILING'
      puts argument
      puts args[0]
      return
    end

    if argument =~ /this_test_is/
      puts 'FOUND THIS TEST IS'
      puts argument
      puts args[0]
      return
    end

    if argument =~ /this_works=/
      instance_variable_set("@#{argument.to_s.chop}", args[0])
      return
    else
      return instance_variable_get("@#{argument}").to_s
    end
  end
end

test = Whosebug.new("post")
test.this_works = true
puts "IT WORKED: " + test.this_works
test.this_test_is.failing

给我以下输出:

ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]

IT WORKED: true
FOUND THIS TEST IS
this_test_is

undefined method `failing' for nil:NilClass
(repl):44:in `<main>'

我要做的是将其视为变量和值对。我想知道如何做这两种情况:

A:识别this_test_is并将其作为变量存储字符串(或符号即可)failing.

B:将 failing 识别为变量,如果我看到 this_test_is,则将 failing 设置为 true,而不是 false,如果我发现this_test_is_not.

提前致谢!

您需要添加某种递归:

class Whosebug
  def initialize(name)
    @name = name
  end

  def method_missing(argument, *args)
    argument = argument.to_s

    if argument =~ /failing/
      puts 'FOUND FAILING'
      puts argument
      puts args[0]
      return
    end

    if argument =~ /this_test_is/
      puts 'FOUND THIS TEST IS'
      puts argument
      puts args[0]
      return Whosebug.new("this_test_is")
    end

    if argument =~ /this_works=/
      instance_variable_set("@#{argument.to_s.chop}", args[0])
      return
    else
      return instance_variable_get("@#{argument}").to_s
    end
  end
end

test = Whosebug.new("post")
test.this_works = true
puts "IT WORKED: " + test.this_works
test.this_test_is.failing

打印这个:

IT WORKED: true
FOUND THIS TEST IS
this_test_is

FOUND FAILING
failing