Ruby 元编程问题:关于动态创建方法

runup · 2015年12月26日 · 最后由 runup 回复于 2015年12月28日 · 2002 次阅读

对元编程第一版第二章内容的一段代码进行了改写,但是出现了问题,代码如下:

class Ds
  def get_mouse_info
    puts "this is the mouse information"
  end

  def get_cpu_info
    puts "this is the cpu information"
  end

  def get_keyboard_info
    puts "this is the keyboard information"
  end
end

class Computer
  def initialize(data_source)
    @data_source = data_source
    data_source.methods.grep(/^get_(. )_info$/){ Computer.define_component $1 }
  end

  def self.define_component(name)
    define_method(name){
      puts "get the #{name} information in the computer"
    }
  end

  # define_component :mouse
  # define_component :cpu
  # define_component :keyboard
end

cp = Computer.new(Ds.new)
cp.mouse

显示的是 undefined method mouse 错误,自己尝试了几次修改,但是没有发现错误原因,请帮忙指正,感谢。

问题解决:因为“.”是可以匹配任何“一个”字符,因此这里(.)不能匹配 mouse,因为 mouse 有五个字符,所有正确的做法是应该使用(.*)或者(.+)的方法匹配任意多的字符,其中前者表示重复 0 次及以上,后者表示重复 1 次及以上。

你把定义 mouse 方法的语句注释掉了

#1 楼 @adamshen

data_source.methods.grep(/^get_(. )_info$/){ Computer.define_component $1 }

这句代码可以实现定义 mouse

/^get_(.+)_info$/

#2 楼 @runup 哈哈 不好意思。 前面的正则表达式是不是少个 + 号,点后面跟个空格能够匹配多个字符吗?

#4 楼 @adamshen ok,是这个问题~

#3 楼 @rei 谢谢指正。

问题解决:因为“.”是可以匹配任何“一个”字符,因此这里(.)不能匹配 mouse,因为 mouse 有五个字符,所有正确的做法是应该使用(.*)或者(.+)的方法匹配任意多的字符,其中前者表示重复 0 次及以上,后者表示重复 1 次及以上。

刚翻了下书,书上写的的确是点和空格,楼主被坑了。

#8 楼 @lolychee 第一版有问题,不过第二版改过来了。

#9 楼 @runup 惭愧。我最近也在看元编程。这本书看了三遍了,这个错误竟然没看出来。我原来看的也是第一版。一直以为是第二版。

#10 楼 @torubylist 代码自己执行一遍就好了

楼主请不要在标题上面加已解决几个字,你可以在最后个回复上面说明 列表好乱

需要 登录 后方可回复, 如果你还没有账号请 注册新账号