ruby - Understanding self with method chaining -


i'm trying understand self in ruby.

in code pasted below, if create new instance of animal with

fox = animal.new.name("fox").color("red").natural_habitat("forest").specie("mammal")

and call

fox.to_s

it not if not return self in every method.

why need self in every method? isn't variable saved once create new animal?

class animal   def name(name)     @name = name     self   end   def specie(specie)     @specie = specie     self    end   def color(color)     @color = color     self    end   def natural_habitat(natural_habitat)     @natural_habitat = natural_habitat     self    end   def to_s     "name: #{@name}, specie: #{@specie}, color: #{@color}, natural habitat: #{@natural_habitat}"   end     end 

this pattern used infrequently in ruby, it's more common in languages java , javascript, it's notably rampant in jquery. part of reason why verbosity you're describing here, , secondly because ruby provides convenient mutator generator in form of attr_accessor or attr_writer.

one problem these accessor/mutator dual purpose methods ambiguity. implementation have incomplete, you're unable read them. need this:

def color(*color)   case (color.length)   when 1     @color = color     self   when 0     @color   else     raise argumenterror, "wrong number of arguments (%d 0)" % color.length   end end 

that's whole lot of code implement can used in 2 ways:

animal.color('red') animal_color = animal.color 

if want use these, you'll need write own meta-programming method can generate them, though i'd highly discourage going down path in first place. use attr_accessor methods , options hash.

here's equivalent ruby pattern:

# up-front assignment via hash animal = animal.new(   name: 'fox',   color: 'red',   natural_habitat: 'forest',   specie: 'mammal' )  # assignment after fact animal.color = 'white' 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -