From: Mike Stok Date: 2013-03-09T23:44:12+09:00 Subject: Re: Confusion with unary operator overidding + and - can be both unary and binary operators, so there are differently named methods for the different operations. http://www.rubyinside.com/rubys-unary-operators-and-how-to-redefine-their-functionality-5610.html might be intresting to you . Hope this helps, Mike On 2013-03-09, at 9:07 AM, "Kumar R." wrote: > I was trying to learn the operator over-ridding in Ruby. So i used the > below in my IRB. > >>> class Banner < String >>> def + > ?> upcase >>> end >>> def - > ?> downcase >>> end >>> end > => nil >>> ban = Banner.new("hi") > => "hi" >>> +ban > NoMethodError: undefined method `+@' for "hi":Banner > from (irb):22 > from C:/Ruby193/bin/irb:12:in `
' > > Now after seeing the error in the `IRB` i corrected definition of `+` > and `-` as below, which in turn fixed the code. > >>> class Banner < String >>> def +@ >>> upcase >>> end >>> def -@ >>> downcase >>> end >>> end > => nil >>> ban = Banner.new("hi") > => "hi" >>> +ban > => "HI" > > But my confusion is with the logical necessity of that `@` operator? > > Again I tried to over-ride `!` as below: > >>> class Banner >>> def ! >>> reverse >>> end >>> end > => nil >>> !ban > => "ih" >>> not ban > => "ih" > > But here I didn't need to use that `@` operator. > > Can anyone help me to understand why `@` was needed with `+` and `-` but > not with `!`? > > Thanks > > -- > Posted via http://www.ruby-forum.com/. -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.