On Nov 30, 2007 12:54 PM, Nathan Viswa <nathanv / rogers.com> wrote:
> Need help to understand how the marked <<< def works. Thanks
>
> class Person
>   def initialize(lname, fname)
>     @lname = lname
>     @fname = fname
>   end
>
>   def lname
>     return @lname
>   end
>
>   def fname
>     return @fname
>   end
>
>   def lname=(myarg)          # see = <<<
>     @lname = myarg
>   end

You are not defining an equals method here (=).  You are defining the
method lname=.  The parser will look for this method before deciding
it's an assignment to variable.

>
>   def fname=(myarg)
>     @fname = myarg
>   end
> end
>
> steve = Person.new("Litt", "Stove")
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
> steve.fname = "Steve"
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
>
> steve = Person.new("Litt", "Stove")
>
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
> steve.fname = "Steve"
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
>
> #steve.fname("Steve") # err

The fname method as you have defined it does not take a parameter.  It
simply returns the fname.  The correct way to call it is steve.fname
(returns Steve)

>
> #steve.lname("Nathan") # err  ????
> steve.lname() #
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
>
> steve.lname = "Nat" #
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
>
> steve.lname() #
> print "My name is ", steve.fname, " ", steve.lname, ".\n"
>
>
> I:\RubyNV>zzz-tut13-class.rb
> My name is Stove Litt.
> My name is Steve Litt.
> My name is Steve Litt.
> My name is Steve Nat.
> My name is Steve Nat.
>
> I:\RubyNV>
>
> XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
>
> if i use it stand alone it does not work!!
>
> class Person
>   def initialize(lname)
>     @lname = lname
>   end
>
>   def lname=(myarg)      # see = <<<
>     @lname = myarg
>        end
>
> end
>
> steve = Person.new("Viswa")
>
> #puts steve.lname, 'x1' # err undefined methid lname

This time you left out the lname method in the class.

> #puts steve.lname(), 'x2' # err as above
> #puts steve.lname("nv"), 'x2' # err as above
>
> #steve.lname = "Nat" #
>
> #puts steve.lname, 'x2' #  err undefined methid lname
> #puts steve.lname(), 'x3' # # err undefined methid lname
>
> #steve.lname = "Nat" #
> #print "My name is ", steve.lname, ".\n" #err
>
> #steve.lname() # err
> #print "My name is ", steve.lname, ".\n"# err
> --
> Posted via http://www.ruby-forum.com/.
>
>

You have a getter and a setter ... 2 methods #lname and #lname=

Note that this is almost exactly the same thing.  It builds those 2
methods for you.

class Peep
  attr_accessor :name
end

p = Peep.new
p.name = "Smith"
puts p.name # returns Smith
puts p.methods.grep /name/ #gives you name and name=

Todd