Ruby ruby 元编程练习

dingzhihu · 2012年11月13日 · 最后由 tumayun 回复于 2012年11月13日 · 3132 次阅读

做一个元编程练习时被难倒了,贴出来,看看各位有啥好主意 http://ruby-metaprogramming.rubylearning.com/html/Exercise_1.html

#1 楼 @themorecolor 应该是获取 a,@a,@@a 的值吧

这种练习意义大么?

#3 楼 @chenge 实际意义不大,但对理解元编程应该还是很有帮助的

这个局部变量 a 应该取不出来的,只能说是最后的有效值返回

这种时候不是应该看书或者看文档么

class A
  def initialize
    @a = 11
    @@a = 22
    a = 33
  end
  @a = 1
  @@a = 2
  a = 3
end

最后 end 前的三行赋值代码我是不是可以理解成跟 java 的 static 块方法一样的功能?

#7 楼 @ywjno static 块方法是在类被加载的时候调用的,但是 Ruby 在载入这个文件就运行了,参见镐头书 "compile time? run time? any time!" 那一节...

#1 楼 @themorecolor #3 楼 @chenge #5 楼 @tumayun #7 楼 @ywjno

网上找到一个解决方案 class_local_a = class A def initialize @a = 11 @@a = 22 a = 33 end @a = 1 @@a = 2 a = 3 end

p A.instance_variable_get(:@a) #ok

p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9'

p class_local_a

p A.new.instance_variable_get(:@a)

p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9'

p A.new.method(:initialize).call

最后一个 a 可以这么取:

three = class A
  ...
  a = 3
end

个人认为研究这个意义不大,估计睡一晚就忘了。

我觉得很有意思阿。

用到的时候再看文档就 OK. 学了 3 天就忘。

最后一个 a 还可以这么取: ruby 1.9.x

class A
   ...
   a = 3
end.tap{|a| p a}

@dingzhihu p class_local_a 这个是什么方法

靠 没看全 其实真心感觉没意思的 多看看书,这些都是浮云

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