Tag: instance eval

使用class_eval和instance_eval访问Ruby类变量

我有以下内容: class Test @@a = 10 def show_a() puts “a: #{@@a}” end class << self @@b = '40' def show_b puts "b: #{@@b}" end end end 为什么以下工作: Test.instance_eval{show_b} b: 40 => nil 但我不能直接访问@@b ? Test.instance_eval{ @@b } NameError: uninitialized class variable @@b in Object 同样,以下工作 t = Test.new t.instance_eval{show_a} a: 10 => nil 但是以下失败了 t.instance_eval{ […]

带有attr_accessor的类上的Ruby instance_eval

我理解instance_eval和class_eval之间的基本区别。 我在玩游戏时发现的是涉及attr_accessor奇怪之attr_accessor 。 这是一个例子: A = Class.new A.class_eval{ attr_accessor 😡 } a = A.new ax = “x” ax => “x” # … expected A.instance_eval{ attr_accessor :y } Ay = “y” => NoMethodError: undefined method `y=’ for A:Class ay = “y” => “y” # WHATTT? 怎么样: instance_eval没有在我们的A类(对象)的访问器上 然后它实际上把它添加到A的实例?

Instance_eval不适用于do / end块,仅适用于{} -blocks

如果我有课: class KlassWithSecret def initialize @secret = 99 end end 并运行: puts KlassWithSecret.new.instance_eval { @secret } 它打印99,但如果我运行: puts KlassWithSecret.new.instance_eval do @secret end 它返回一个错误: `instance_eval’: wrong number of arguments (0 for 1..3) (ArgumentError) 为什么我不能使用带有instance_eval do / end块? PS我使用的是Ruby 2.1.0。

没有提供Instance_eval块?

有人知道是什么导致了这个错误吗? 我正在尝试制作基本的机架应用程序。 App.rb => class Cherry class < “text/plain”}, “Hello World”] end end end Config.ru => require ‘app’ run Cherry.app do print_start_message end 编辑:显然我忘了包含错误woops: /local/www/cherry/lib/app.rb:12:in ‘instance_eval’: block not supplied (ArgumentError)