在Ruby中的块中保存实例变量
调用lambda@description时,我看不到实例变量@model的值。这可能吗?我只看到“非常好。”当我打电话给show_描述时。 提前谢谢在Ruby中的块中保存实例变量,ruby,block,instance-variables,Ruby,Block,Instance Variables,调用lambda@description时,我看不到实例变量@model的值。这可能吗?我只看到“非常好。”当我打电话给show_描述时。 提前谢谢 class Car def initialize(model) @model = model end def description @description = lambda{yield} end def show_description @description.call end end c
class Car
def initialize(model)
@model = model
end
def description
@description = lambda{yield}
end
def show_description
@description.call
end
end
c = Car.new("Ford")
c.description{"#{@model} is very good."}
puts c.show_description # => " is very good."
您可以这样做:
class Car
attr_reader :model
def initialize(model)
@model = model
end
def description
@description = lambda{yield}
end
def show_description
@description.call
end
end
c = Car.new("Ford")
c.description{"#{c.model} is very good."}
puts c.show_description #Ford is very good.
c.description{{{@model}非常好。}
不会告诉你你想要什么。关键是,您通过的块可以访问外部作用域,在该作用域中找不到变量@model
,因此@model
是nil
。它被称为封装,因此,外部世界无法直接知道/访问对象的状态,在您的情况下,对象是c
。在这里,对象的状态意味着实例变量的值位于对象c
。但是使用方法,您可以读取/更新对象的状态
因此,按c.description{{c.model}做是非常好的。}
您的代码可以重新编写为:
class Car
attr_reader :model
def initialize(model)
@model = model
end
def description
@description = yield
end
def show_description
@description
end
end
c = Car.new("Ford")
c.description{"#{c.model} is very good."}
puts c.show_description
# >> Ford is very good.
@description
,因此最好通过变量访问该实例,而不是使用yield
def description &pr
@description = pr
end
@description
,即在Car
的实例中
def show_description
instance_exec(&@description)
end
c = Car.new("Ford")
c.description{"#{@model} is very good."}
puts c.show_description
# => Ford is very good.
顺便说一句,你可以简化
“{@model}非常好。”
到“{@model非常好。”
@CarySwoveland是的,它是正确的cvar
,gvar
abdivar
不需要{..}
,只要
就足够了。示例->@x=12=>12>“我有#@x支笔”=>“我有12支笔”
非常感谢。一个来自BasicObject的方法,我不知道。