1 / 8

Ruby Learning: Creating Iterators & Using Enumerable Class

Learn how to add iterator support in Ruby by mixing in the Enumerable class and creating custom methods. Explore processing command-line arguments and working with environments and configurations.

trotmana
Download Presentation

Ruby Learning: Creating Iterators & Using Enumerable Class

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Grabbag IV - the fourth installment of the Trilogy Learning Ruby - 14

  2. Creating Iterators • Adding iterator support (that is, .each, .collect, .inject, etc., etc.) is easy • Simply mixin the Enumerable class into your class • Use include Enumerable near the top of your class code • Create an each method that makes sense for your class

  3. Ethernet.each class Ethernet include Enumerable def each yield @dest yield @src yield @type_len yield @payload end # of each. ... end # of Ethernet.

  4. Slurping Files string_of_lines = IO::read( "/etc/passwd" ) array_of_lines = IO::readlines( "/etc/passwd" )

  5. Processing Command-line Args # Remember: all arguments are passed in as strings! ARGV.each { |arg| puts arg } option1, option2 = ARGV.collect { |arg| arg } if ARGV.length == 0 fail "Please supply some parameters!" end # of if.

  6. Environments and Configurations ENV.keys.each { |key| print "#{key} -> ", ENV[key], "\n" } ENV.collect() do |key, value| print "#{key} --> #{value} \n" end # of do require 'rbconfig' include Config CONFIG.keys.sort.each do |key| print "#{key} -> ", CONFIG[key], "\n" end # of do.

  7. Where Are My Modules? ruby -e 'puts $:' /usr/local/lib/site_ruby/1.8 /usr/local/lib/site_ruby/1.8/i486-linux /usr/local/lib/site_ruby/1.8/i386-linux /usr/local/lib/site_ruby /usr/lib/ruby/1.8 /usr/lib/ruby/1.8/i486-linux /usr/lib/ruby/1.8/i386-linux .

  8. More ... Ruby So Far Look for ways to do cool stuff with Ruby. For example: • A project proposal for 4th Year: Create a Ruby extension that allows for the manipulation of the Torque Game Engine from within any Ruby program.

More Related