怎么写正确的方法?

时间:2010-09-23 11:24:25

标签: ruby class methods

class Mycompute

  def initialize(str)
    @str=str
  end

  def values
    @@result=@str
  end

  def up
    @@result.upcase
  end

end
irb(main):012:0> Mycompute.new("Abc").values

=> "Abc"
irb(main):013:0>

irb(main):014:0* Mycompute.new("Abc").up
=> "ABC"
irb(main):015:0> Mycompute.new("Abc").values.up

NoMethodError: undefined method `up' for "Abc":String
  from (irb):15
  from :0

如何让Mycompute.new("Abc").values.up工作?

1 个答案:

答案 0 :(得分:0)

values返回的对象需要up

class Mycompute

  def initialize(str)
    @str=str
  end

  def values
    @@result=@str

    def @@result.up
      self.upcase
    end

    @@result
  end

  def up
    @@result.upcase
  end

end

这很有效。

Mycompute.new("Abc").values #=> "Abc"
Mycompute.new("Abc").up #=> "ABC"
Mycompute.new("Abc").values.up #=> "ABC"