Operator overloading?

lass Whatever
    attr_accessor :number, :str
    def initialize(number)
        @number = number
        @str = "Your number is : ( #{@number} )"
    end
end
def >>a # I wanted to use this operator in order to put an object of
class whatever
    puts a.str
end
object = Whatever.new(10)

···

object # why doesn't it work?

--
Posted via http://www.ruby-forum.com/\.

Your syntax is off. Here's an example of defining #>>

class X
  def >>(other)
    p [self, other]
  end
end

x = X.new
y = 1
x >> y #=> [#<X:0x0000010096aec8>, 1]

···

On Fri, Aug 26, 2011 at 1:36 PM, jack jones <shehio_22@hotmail.com> wrote:

def >>a # I wanted to use this operator in order to put an object of
class whatever
   puts a.str
end
object = Whatever.new(10)
>>object # why doesn't it work?

jack jones wrote in post #1018639:

         # why doesn't it work?

  your syntax is not quite ruby... maybe something like this is what
you want?

    class Whatever
  attr_accessor :number, :str

  def initialize(number)
    @number = number
    @str = "Your number is : ( #{@number} )"
  end

  def >>
    puts @number
    puts @str
  end

    end

    object = Whatever.new(10)
    object.>>

    # returns:
    => 10
    => Your number is : ( 10 )

  note that you don't need to set :number and :str as atrr_accessors for
this to work... if you want to leave them as accessors, you don't
really need the '>>' method, you could do something like this instead:

    class Whatever
  attr_accessor :number, :str

  def initialize(number)
    @number = number
    @str = "Your number is : ( #{@number} )"
  end

    end

    object = Whatever.new(10)
    puts object.number
    puts object.str

    # also returns:
    => 10
    => Your number is : ( 10 )

- j

···

--
Posted via http://www.ruby-forum.com/\.