Sunday, August 5, 2012

Working with Enumerables Today.


An Exercise from chapter 10 of David Black's The Well Grounded Rubyist:

1.9.3p194 :001 > class Rainbow
1.9.3p194 :002?>   include Enumerable
1.9.3p194 :003?>   def each
1.9.3p194 :004?>     yield "red"
1.9.3p194 :005?>     yield "orange"
1.9.3p194 :006?>     yield "yellow"
1.9.3p194 :007?>     yield "green"
1.9.3p194 :008?>     yield "green"
1.9.3p194 :009?>     yield "blue"
1.9.3p194 :010?>     yield "indigo"
1.9.3p194 :011?>     yield "violet"
1.9.3p194 :012?>     end
1.9.3p194 :013?>   end
 => nil

then...

1.9.3p194 :025 > r = Rainbow.new
 => #<Rainbow:0x007f8bea15d0d8> 
1.9.3p194 :026 > r.each do |color|
1.9.3p194 :027 >     puts "Next color: #{color}" 
1.9.3p194 :028?>   end
Next color: red
Next color: orange
Next color: yellow
Next color: green
Next color: green
Next color: blue
Next color: indigo
Next color: violet
 => nil 

This is just the beginning, but a key part of what I need to know to be an effective developer.

and more...


1.9.3p194 :029 > r = Rainbow.new
 => #<Rainbow:0x007f8bea148fe8>
1.9.3p194 :032 > y_color = r.find {|color| color.start_with?('y') }
 => "yellow"
1.9.3p194 :033 > puts "The first color staring with 'y' is #{y_color}."
The first color staring with 'y' is yellow.
 => nil

Woot! On to more....

No comments:

Post a Comment