繁体   English   中英

基本的Ruby。 为什么此方法返回nil?

[英]Basic Ruby. Why is this method returning nil?

嗨!

我期望#<PrettyThing:0x0055a958175348 @success="anything here">

但是我得到的是'anything here' 知道为什么吗?

class Thing
  attr_accessor :success

  def execute
    self.success = execute!
  rescue
    self.success = false
  ensure
    self
  end
end

class PrettyThing < Thing
  def execute!
    'anything here'
  end
end

p PrettyThing.new.execute # => 'anything here'

确保是一件棘手的事情。 通常,它不返回值,而是返回主块或救援块最后执行的行的返回值,除非存在未捕获的错误,否则将返回错误。 但是,如果您显式返回,则将获得返回值。 这是一个有点非标准和混乱,虽然,因为的意图ensure条款是无声的清理。 最好将返回值移到begin / rescue块之外。

尝试:

class Thing
  attr_accessor :success

  def execute
    self.success = execute!
    self
  rescue
    self.success = false
  end
end

class PrettyThing < Thing
  def execute!
    'anything here'
  end
end

p PrettyThing.new.execute # => <PrettyThing:0x0000000379ea48 @success="anything here">

您编写的代码的execute是返回self.success = execute!的赋值结果self.success = execute! 通过添加self ,可以返回PrettyThing的实例。

如果要链接方法,例如:

class Thing
  attr_accessor :success

  def execute
    self.success = execute!
    self
  rescue
    self.success = false
  end

  def foo
    puts 'foo'
  end

end

class PrettyThing < Thing
  def execute!
    'anything here'
  end
end

p PrettyThing.new.execute.foo # => foo

鉴于您的评论,我想我可能会更喜欢:

class Thing
  attr_accessor :success

  alias success? success

  def foo
    puts 'foo'
  end

end

class PrettyThing < Thing

  def execute
    @success = everything_worked
    self
  end

private

  def everything_worked
    # your logic goes here
    # return true if all is good
    # return false or nil if all is not good
    true
  end

end

pretty_thing = PrettyThing.new.execute
p pretty_thing.success? # => true

如果everything_worked返回falsenil ,那么pretty_thing.success? 也会返回falsenil

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM