Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中的块中保存实例变量_Ruby_Block_Instance Variables - Fatal编程技术网

在Ruby中的块中保存实例变量

在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

调用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 = 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.
  • 由于您将proc实例保存为
    @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
    abd
    ivar
    不需要
    {..}
    ,只要
    就足够了。示例-
    >@x=12=>12>“我有#@x支笔”=>“我有12支笔”
    非常感谢。一个来自BasicObject的方法,我不知道。