ruby programming

Upload: dsunte-wilson

Post on 14-Oct-2015

92 views

Category:

Documents


1 download

DESCRIPTION

Ruby Programming, Rails, Ruby 2.0

TRANSCRIPT

  • RUBY PROGRAMMING

    Course # TE3601 Rev. 3/25/2013

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. i

    7150 Riverwood Drive, Suite J

    Columbia, MD 21046 Tel: 410-290-8383

    Fax: 410-290-9427 http://www.trainingetc.com

    email: [email protected]

    RUBY PROGRAMMING

    Course # TE3601 Rev. 3/25/2013

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. ii

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. iii

    Course Objectives

    At the conclusion of this course, students will be able to: Distinguish and use various Ruby datatypes Master the use of arrays and hashes Build home grown classes Use the extensive pre bundled classes Use the I/O facilities of Ruby to read and write binary and text

    files

    Master the use of Iterators to loop through various data structures

    Use Exceptions in handling various run time errors Create Ruby modules Use the wide variety of Ruby Modules that come with the Ruby

    distribution

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. iv

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v

    Table of Contents

    CHAPTER 1: AN INTRODUCTION TO RUBY What is Ruby? .............................................................................................. 1-2 Installing Ruby .............................................................................................. 1-3 Executing Ruby Code ................................................................................... 1-4 Getting Help.................................................................................................. 1-6 Dynamic Types ............................................................................................. 1-9 Ruby Reserved Words................................................................................ 1-10 Naming Conventions .................................................................................. 1-11 Comments .................................................................................................. 1-12

    CHAPTER 2: STANDARD RUBY DATA TYPES Numbers ....................................................................................................... 2-2 Strings .......................................................................................................... 2-3 Simple Input and Output ............................................................................... 2-9 Converting String Input ............................................................................... 2-10 Regular Expressions................................................................................... 2-11 Time Methods............................................................................................. 2-14

    CHAPTER 3: LANGUAGE COMPONENTS The if Statement......................................................................................... 3-2 The Logical Operators .................................................................................. 3-3 The case Construct...................................................................................... 3-4 Loops............................................................................................................ 3-5 Iterators ........................................................................................................ 3-9 Numeric Iterators ........................................................................................ 3-10 String Iterators ............................................................................................ 3-13 Methods...................................................................................................... 3-16 Odds and Ends........................................................................................... 3-18

    CHAPTER 4: COLLECTIONS Arrays ........................................................................................................... 4-2 Array Operator Methods ............................................................................... 4-5 Array Equality Operator ................................................................................ 4-9 Arrays as Stacks and Queues .................................................................... 4-10 Higher Dimensional Arrays ......................................................................... 4-11 Other Useful Arrays Methods...................................................................... 4-12 Command Line Arguments ......................................................................... 4-13 Hashes ....................................................................................................... 4-14 Common Hash Methods ............................................................................. 4-17 Sorting Hashes ........................................................................................... 4-18 Iterators with Arrays and Hashes................................................................ 4-20 Arrays and Methods.................................................................................... 4-21 Hashes and Methods.................................................................................. 4-22 Named Parameters..................................................................................... 4-23 Symbols...................................................................................................... 4-24

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. vi

    Procs .......................................................................................................... 4-26 Closures ..................................................................................................... 4-28

    CHAPTER 5: CLASSES Objects ......................................................................................................... 5-2 Brief History of OOP ..................................................................................... 5-3 OOP Vocabulary........................................................................................... 5-4 Creating a New Class ................................................................................... 5-6 Using Objects ............................................................................................... 5-8 Defining Operator Methods......................................................................... 5-13 Inheritance.................................................................................................. 5-14 Ancestors.................................................................................................... 5-18 self ........................................................................................................... 5-20 Access Levels - public............................................................................. 5-23 Access Levels private.......................................................................... 5-25 Access Levels - protected ...................................................................... 5-26 Access Levels - Specification ..................................................................... 5-27 Class Data and Class Methods................................................................... 5-28 Adding Methods to Classes and Objects .................................................... 5-30 Special Global Variables............................................................................. 5-31 Scope of Variables...................................................................................... 5-32 Built-in Classes ........................................................................................... 5-33 The Math Class.......................................................................................... 5-34 The NilClass Class ................................................................................. 5-35 TrueClass and FalseClass ................................................................... 5-36 Built-in Class Hierarchy .............................................................................. 5-37

    CHAPTER 6: INPUT AND OUTPUT Introduction................................................................................................... 6-2 Reading from the Standard Input.................................................................. 6-3 Writing to the Standard Output ..................................................................... 6-7 Reading and Writing Disk Files..................................................................... 6-8 Reading Files Using Iterators...................................................................... 6-10 I/O With Command Line Commands .......................................................... 6-12 Seeking About Files.................................................................................... 6-13 tell ........................................................................................................... 6-16 Capturing Data About Files......................................................................... 6-17 Processing Directories................................................................................ 6-18

    CHAPTER 7: EXCEPTIONS Introduction................................................................................................... 7-2 Exception Hierarchy...................................................................................... 7-3 Handling Exceptions ..................................................................................... 7-4 Multiple Rescue Clauses .............................................................................. 7-7 Exceptions are Classes ................................................................................ 7-8 ensure......................................................................................................... 7-9 retry ......................................................................................................... 7-10

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. vii

    raise ......................................................................................................... 7-11 Creating Your Own Exceptions................................................................... 7-13 catch and throw ...................................................................................... 7-14

    CHAPTER 8: MODULES Introduction................................................................................................... 8-2 Using Core Ruby Classes............................................................................. 8-3 Ruby Standard Library.................................................................................. 8-5 require....................................................................................................... 8-6 Search Path.................................................................................................. 8-8 File Organization........................................................................................... 8-9 load ........................................................................................................... 8-12 Modules ...................................................................................................... 8-13 include..................................................................................................... 8-16 Mixins ......................................................................................................... 8-17 Using the Comparable Module ................................................................. 8-20 Collection Classes ...................................................................................... 8-22 yield ......................................................................................................... 8-23 Using the Enumerable Module.................................................................... 8-26

    CHAPTER 9: ODDS AND ENDS Ruby Conventions ........................................................................................ 9-2 Bit Manipulation ............................................................................................ 9-5 Substituting................................................................................................... 9-8 Marshalling ................................................................................................... 9-9 Reflection.................................................................................................... 9-11 grep ........................................................................................................... 9-12 Classes are Objects.................................................................................... 9-13 Aliasing ....................................................................................................... 9-15 Testing........................................................................................................ 9-16 Test::Unit::TestCase......................................................................... 9-17 Testing Your Own Classes ......................................................................... 9-22 Freezing Objects......................................................................................... 9-24 Object Equality............................................................................................ 9-26

  • RUBY PROGRAMMING

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. viii

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-1

    Chapter 1: An Introduction to Ruby

    1) What is Ruby?.......................................................................................................... 1-2

    2) Installing Ruby......................................................................................................... 1-3

    3) Executing Ruby Code .............................................................................................. 1-4

    4) Getting Help ............................................................................................................. 1-6

    5) Dynamic Types ......................................................................................................... 1-9

    6) Ruby Reserved Words........................................................................................... 1-10

    7) Naming Conventions.............................................................................................. 1-11

    8) Comments ............................................................................................................... 1-12

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-2

    What is Ruby?

    In the mid 1990's, the Ruby programming language surfaced in Japan, the home of Ruby's creator, Yukihiro Matsumoto.

    He is usually referred to as Matz.

    Matz knew Python and Perl and thought that each of those languages left something to be desired.

    In particular, he did not like that both Perl and Python were not fully object oriented.

    Since that time, Python has become fully object oriented. Ruby is often compared to Python and Perl, and each language

    community has their own arguments as to why their language is better.

    Ruby has the following technical characteristics. Interpreted rather than compiled Dynamic typing rather than static typing Completely object oriented.

    Like other languages, Ruby has undergone various revisions.

    Version 1.9.3 was released in October of 2011. Version 2.0.0 was released in February of 2013.

    All things concerning Ruby can be located at: http://www.ruby-lang.org/en

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-3

    Installing Ruby

    Instructions for downloading and installing Ruby can be found at the following URL.

    http://www.ruby-lang.org/en/downloads/

    Versions of Ruby are available for download for many different operating systems including:

    Linux Windows Mac OS X

    There are three ways of installing Ruby. Each of the following techniques is explained in more detail at

    the URL listed above.

    Compiling from source Package management systems Third party tools

    One of the more popular tools for installing Ruby in a Linux or

    Mac OS X environment is the Ruby Version Manager (RVM).

    RubyInstaller is an application that can be used to easily install Ruby in a Windows environment.

    RailsInstaller can be used if both Ruby and Rails are to be used in a Windows environment.

    One major benefit of the third party tools is the ability to have different versions of Ruby installed side-by-side on the same computer.

    It is for this reason that RVM has been chosen to install Ruby version 1.9.3 on the Linux machines in the classroom.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-4

    Executing Ruby Code

    Since we will be using Linux here, all of the examples will demonstrate executing programs in a Linux environment.

    To execute a Ruby program from the command line, we will first create an .rb file with your favorite text editor.

    Although not required, the .rb file extension is the industry standard for files containing Ruby code.

    example1.rb

    1. #!/usr/bin/ruby 2. puts "This text is output to the screen when run"

    Once the file is created, how it is executed depends upon the operating system being used.

    In a Linux / Mac OS X environment, the first line of the file usually contains the path to the Ruby interpreter.

    Although not necessary in a Windows environment, it is often used for cases when code developed in a Windows environment might be run in a different environment.

    In a Linux / Mac OS X environment, the file can be made executable with the following command.

    chmod 755 example1.rb

    It can then simply be run with the following command. example1.rb

    Alternatively, the script can be run on all platforms without the need to make it executable with the following command.

    ruby example1.rb

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-5

    Executing Ruby Code

    The execution and output of the script on the previous page is shown below.

    student@localhost:~/rubylabs/examples/1 $ ruby example1.rb This text is output to the screen when run $

    Another way in which Ruby code can be executed is using the interactive Ruby utility named irb.

    This tool (like many others) is automatically included when installing Ruby using third party tools.

    Package management systems may require additional packages to be installed for all the tools to become available.

    The irb utility is demonstrated below. Sample Ruby code, shown in bold below, is typed interactively

    during the running of the irb session.

    Typing exit will terminate the irb session. student@localhost:~/rubylabs/examples/1

    $ irb 1.9.3p392 :001 > 2 + 2 => 4 1.9.3p392 :002 > puts "Hello" Hello => nil 1.9.3p392 :003 > "Hello".reverse => "olleH" 1.9.3p392 :004 > x = "Hello" => "Hello" 1.9.3p392 :005 > puts x Hello => nil 1.9.3p392 :006 > exit $

    Each statement entered is executed, and the results are

    displayed on the console. Some statements have the result of nil, the Ruby version of Python's None.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-6

    Getting Help

    There are various ways in which a Ruby programmer can get help with the Ruby language.

    A good starting point is the following URL. http://www.ruby-lang.org/en/documentation/

    As shown above, there are links to navigate to places specific

    to the various help topics.

    The reference links listed below may be worth bookmarking in your browser for easy reference.

    The Ruby Core Reference http://www.ruby-doc.org/core-1.9.3

    The Ruby Standard Library Reference

    http://www.ruby-doc.org/stdlib-1.9.3/

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-7

    Getting Help

    Another tool for getting help in Ruby is the Ruby Index (ri) command line tool.

    The ri tool can be used to view the Ruby documentation off-line.

    A closely related tool to ri is Ruby Documentation (RDoc).

    RDoc is a documentation system that creates nicely formatted documentation from commented source files.

    It is available through the rdoc command line tool. ri is used to display the information generated by rdoc from

    the Ruby source files.

    The documentation that is displayed is in the format of Unix/Linux man pages.,

    The following example shows how to display documentation for the String.

    student@localhost:~/rubylabs/examples/1

    $ ri String $

    student@localhost:~/rubylabs/examples/1

    = String < Object

    ------------------------------------------------------------------------------

    = Includes: Comparable (from ruby site)

    (from ruby site) ------------------------------------------------------------------------------

    A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.

    Typing the letter q will quit out of the documentation.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-8

    Getting Help

    The example below demonstrates how to get more specific information, like the length method of the String class.

    student@localhost:~/rubylabs/examples/1

    $ ri String.length $

    student@localhost:~/rubylabs/examples/1

    = String.length

    (from ruby site) ------------------------------------------------------------------------------

    str.length -> integer str.size -> integer

    ------------------------------------------------------------------------------

    Returns the character length of str.

    The RDoc files created during the installation of Ruby by RVM can be found at the following location on your hard drive. /home/student/.rvm/docs/ruby-1.9.3-p392/rdoc/index.html

    The format of the HTML files located in the rdoc directory

    listed above is similar, but not identical, to those found in the online documentation files for Ruby, specified earlier.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-9

    Dynamic Types

    With the Ruby environment in place, the following program demonstrates the dynamic type system of the Ruby language.

    Ruby programmers do not define the type of a variable. Its type varies with the data that it holds. The class method can be used to determine the type of the

    object being referenced by the variable. class.rb

    1. #!/usr/bin/ruby 2. w = "Hello" 3. x = 123 4. y = 249.35 5. z = true 6. puts w.class, x.class, y.class, z.class

    student@localhost:~/rubylabs/examples/1

    $ruby class.rb String Fixnum Float TrueClass $

    Note that each of the following will yield the data type of Class.

    Fixnum.class String.class

    You can also make a test to determine the class of a variable. x = 123 if ( x.class == Fixnum ) puts "It's an integer" end

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-10

    Ruby Reserved Words

    Several words we have seen are used for special purposes in the Ruby language.

    These words are reserved and cannot be used as the names of variables or methods within your code.

    The list of reserved words is shown below.

    Ruby Reserved Words BEGIN class in super

    END def module then

    __ENCODING__ defined? next true

    __END__ do nil undef

    __FILE__ else not unless

    __LINE__ elsif or until

    alias end redo when

    and ensure rescue while

    begin false retry yield

    break for return

    case if self

    Only a few of these reserved words have been used in the examples so far.

    The majority of them will be explained as we proceed through the course.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-11

    Naming Conventions

    Ruby is a case sensitive language. It means that name and Name are two different identifiers.

    Identifiers in Ruby can be created from alphanumeric characters and the underscore (_) character.

    An identifier cannot begin with a number.

    Ruby enforces some naming conventions. If an identifier starts with a capital letter, it is a constant. If it starts with a dollar sign ($), it is a global variable. If it starts with @, it is an instance variable. If it starts with @@, it is a class variable.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-12

    Comments

    A comment in Ruby starts with # and continues to the end of the line.

    There are several comments in the code below. comments.rb

    1. #!/usr/bin/ruby 2. # This program contains several comments 3. x = 10 # a Fixnum 4. y = "Hello There" # a String 5. z = "# This is NOT a comment"

    When the above program is executed from the command

    line, the shell will interpret the first line of the program and use the shebang to find the Ruby interpreter and run the script.

    Otherwise, the Ruby interpreter will treat the first line as a Ruby comment just like the others in the file.

    A multi-line or block comment can be used as follows. block.rb

    1. #!/usr/bin/ruby 2. puts "Before" 3. =begin 4. This next line is not executed 5. puts "Inside of begin/end block 6. =end 7. puts "After"

    The output from the above program is shown below.

    Before After

    Any lines between the =begin and the =end are not

    executed by the Ruby interpreter.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-13

    Exercises

    1. Start the irb command line tool and experiment with some Ruby expressions.

    2. Use the ri command line tool to get information for the Fixnum datatype.

    Next, use the ri tool again to get specific information about one of the instance methods listed in the documentation for Fixnum.

    3. Locate the RDoc documenation for the Fixnum class in the local documentation.

    Recall that local Ruby documentation can be found at: /home/student/.rvm/docs/ruby-1.9.3-p392/rdoc

    4. Locate the online documentation for the Fixnum class.

    Recall that the online Ruby Core Reference can be found at: http://www.ruby-doc.org/core-1.9.3/

    5. Create a file named first.rb in the following directory.

    /home/student/rubylabs/exercises/1 In that file, assign values to several variables. Perform a few operations with them. Print the values of the variables.

  • RUBY PROGRAMMING CHAPTER 1: AN INTRODUCTION TO RUBY

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-14

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-1

    Chapter 2: Standard Ruby Data Types

    1) Numbers.................................................................................................................... 2-2

    2) Strings ....................................................................................................................... 2-3

    3) Simple Input and Output ........................................................................................ 2-9

    4) Converting String Input ........................................................................................ 2-10

    5) Regular Expressions .............................................................................................. 2-11

    6) Time Methods......................................................................................................... 2-14

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-2

    Numbers

    Ruby provides a number of built-in number classes. We will explore some of the more commonly used classes.

    The Integer class is the basis for the two classes Fixnum and Bignum.

    A Fixnum holds Integer values that can be represented natively.

    If any operation on a Fixnum exceeds this range, the value is automatically converted to a Bignum.

    The Float class represents inexact real numbers using the native architecture's double-precision floating point representation.

    Almost all applications will involve some degree of integer and floating point arithmetic.

    Ruby's Arithmetic Operators are shown in the table below. Operator Name Description

    + Addition Adds values on either side of the operator

    - Subtraction Subtracts right operand from left operand

    * Multiplication Multiplies values on either side of the operator

    / Division Divides left operand by right operand

    % Modulus Divides left operand by right operand and returns remainder

    ** Exponent Performs exponential (power) calculation on operators

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-3

    Strings

    A string is a collection of zero or more characters. Support for strings is available in Ruby from the built-in String

    class.

    A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters.

    Users of strings should be aware of the methods that modify the contents of a String object.

    Typically, methods with names ending in "!" modify their receiver.

    Methods without a "!" typically return a new String.

    Strings can be delimited using either double quotes (") or single quotes (').

    The double quotes are designed to interpret escaped characters such as new lines and tabs so that they appear as actual new lines and tabs when the string is rendered for the user.

    Single quotes, however, display the actual escape sequence (for example displaying \n instead of a new line).

    The program on the following page demonstrates the difference between single and double quoted literal strings.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-4

    Strings quotes.rb

    1. #!/usr/bin/ruby 2. s1 = "0 \t 1 \t 2 \t 3 \t 4 \n5 \t 6 \t 7 \t 8 \t 9" 3. s2 = '0 \t 1 \t 2 \t 3 \t 4 \n5 \t 6 \t 7 \t 8 \t 9' 4. puts "A double quoted String:" 5. puts s1 6. puts 7. puts "A single quoted String:" 8. puts s2

    The output from the above program is shown below.

    A double quoted String: 0 1 2 3 4 5 6 7 8 9

    A single quoted String: 0 \t 1 \t 2 \t 3 \t 4 \n5 \t 6 \t 7 \t 8 \t 9

    You can substitute the value of any Ruby expression into a double quoted string using the sequence #{} as demonstrated in the program below.

    interpolation.rb

    1. #!/usr/bin/ruby 2. x = 10 3. y = 20 4. puts "x = #{x} and y = #{y}" 5. puts "x + y = #{x + y}"

    The output from the above program is shown below.

    x = 10 and y = 20 x + y = 30

    If single quotes were used in the code, the expressions

    would not have been evaluated.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-5

    Strings

    Several methods in the String class are shown below. strings.rb

    1. #!/usr/bin/ruby 2. text = "this is some text" 3. puts "The original text is: " + text 4. puts "The length of the text is #{text.length}" 5. puts "Capitalized: " + text.capitalize 6. puts "Upper Case: " + text.upcase 7. puts "Reversed: " + text.reverse 8. puts "Hello " * 5

    The output from the above program is shown below.

    The original text is: this is some text The length of the text is 17 Capitalized: This is some text Upper Case: THIS IS SOME TEXT Reversed: txet emos si siht Hello Hello Hello Hello Hello

    The String class also has a split method, which returns an array of strings based on the supplied delimiter.

    splitting.rb

    1. #!/usr/bin/ruby 2. text = "this,is,comma,separated" 3. result = text.split(",") 4. puts result

    The output from the above program is shown below.

    this is comma separated

    Arrays will be covered in detail in a later chapter.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-6

    Strings

    Strings are references, so even though assignment is simple, be aware of the following.

    string_reference.rb

    1. #!/usr/bin/ruby 2. message = "This is a string" 3. text = message 4. text.upcase! 5. puts message, text

    The output from the above program is shown below.

    THIS IS A STRING THIS IS A STRING

    If you truly want a separate string, you can use the dup method as shown below.

    string_dup.rb

    1. #!/usr/bin/ruby 2. message = "This is a string" 3. text = message.dup 4. text.upcase! 5. puts message, text

    The output from the above program is shown below.

    This is a string THIS IS A STRING

    The next page discusses some of the more common String methods.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-7

    Strings

    The following two methods return the zero based position of one string within the "host" string.

    index returns the left-most position. rindex returns the right-most position.

    The special value of nil is returned by both methods if the host string does not contain the string.

    indexes.rb

    1. #!/usr/bin/ruby 2. txt = "More than 10 years ago"; 3. puts "Left a : #{txt.index("a")}" 4. puts "Middle a from Left: #{txt.index('a', 4)}" 5. puts "Right a: #{txt.rindex('a')}" 6. puts "Middle a from Right: #{txt.rindex('a', -9)}"

    The output from the above program is shown below.

    Left a : 7 Middle a from Left: 7 Right a: 19 Middle a from Right: 7

    Stripping whitespace from a String can be done with the following methods.

    strip and strip! Removes leading and trailing whitespace

    lstrip and lstrip! Removes leading whitespace

    rstrip and rstrip! Removes trailing whitespace

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-8

    Strings

    A string can also be accessed in whole or in parts using the element reference operator [] (square brackets).

    As we will see later in the course, this operator (like most operators in Ruby) is implemented as a method of the data type.

    The example below demonstrates the versatility embedded within the [] operator.

    elements.rb

    1. #!/usr/bin/ruby 2. s = "this is an example string" 3. puts s[0] # t in Ruby 1.9.x 4. # 116 in prior versions of Ruby 5. puts s[0].chr # t in all versions of Ruby 6. puts s[5,7] # start at pos 5 and get 7 chars 7. puts s[-6,3] # start 6 from the right end 8. s[0,0] = "Hello" #insert at position 9. puts s 10. 11. #start at position 0 replace 15 chars with something 12. s[0,15] = "something" 13. puts s

    The output from the above program is shown below.

    t t is an e str Hellothis is an example string something example string

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-9

    Simple Input and Output

    Below is a small program that illustrates how a program might get some simple input from a user.

    input.rb

    1. #!/usr/bin/ruby 2. print "Enter a line: " 3. line = gets 4. puts line.class, line.length

    The output from the above program is shown below.

    Enter a line: Michael String 8

    There are a few things to notice about the program. The gets method gets a single line from the user.

    The line contains the newline character. The returned data is of type String.

    The puts method outputs data to the display.

    print is like puts except that it does not display a newline.

    If you wished to do some arithmetic with a line obtained with gets, you would have to convert the line to either an integer or a float.

    The following methods are widely used in Ruby programs. to_i converts to integer to_f converts to float to_s converts to String

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-10

    Converting String Input

    A few conversion methods are shown below. convert.rb

    1. #!/usr/bin/ruby 2. print "Enter a line: " 3. line = gets.chop 4. sum = line.to_i + line.to_i 5. puts line + " plus " + line + " is " + sum.to_s

    The output from the above program is shown below.

    Enter a line: 10 10 plus 10 is 20

    The chop method removes the last character of a string. There is a similar method named chomp that removes the last

    character of a string only if it is a newline character.

    The to_i method will work fine for integer input but will truncate string or floating point data.

    The + method is used to concatenate two strings. The to_s method may be needed to convert data to string data

    before it is concatenated.

    Below is a simplified version of the puts (or print) method, using interpolation.

    puts "#{line} plus #{line} is #{sum}"

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-11

    Regular Expressions

    Often, a program needs to determine if a string matches a certain pattern.

    Is it all digits? Is it all alphabetic? Is it an email address?

    Modern programming languages deal with these problems by using regular expressions.

    A regular expression is a way of representing a pattern by using special symbols.

    Once a regular expression has been encoded, it is used to determine if a string matches the pattern expressed by the regular expression.

    The regular expression matching operator is =~. A test to determine if a string matches a pattern might look like

    this.

    if string =~ /PATTERN/ do something end

    A few of the special symbols used by Ruby in the formulation of regular expressions are shown on the next page.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-12

    Regular Expressions

    The following characters are used to anchor the pattern. Symbol Meaning Example

    ^ At the beginning /^the/

    $ at the end /the$/

    Here is a simple example. regex1.rb

    1. #!/usr/bin/ruby 2. puts "Please enter some text:" 3. line = gets.chomp 4. 5. result = line =~ /^the/ 6. print "result data type: ", result.class, "\n" 7. print "result value: ", result, "\n" 8. 9. result = "ends with the" =~ /the$/ 10. print "result data type: ", result.class, "\n" 11. print "result value: ", result, "\n"

    The output from the above program is shown below.

    Please enter some text: hello result data type: NilClass result value: result data type: Fixnum result value: 10

    You can use the i character at the end of the pattern to ignore the case.

    line =~ /^the/i

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-13

    Regular Expressions

    Other special symbols used to match patterns appear in the following table.

    Symbol Meaning Example . Any character /A.B/ [ ] Alternatives /s[uoi]n/ \w Letter or digit / \w\w / \s Whitespace character /^\w\w\s/ \d Digit character / \d\d /

    {m,n} m through n reps of preceding char /A{2,4}B/ ? Zero or one of preceding char /^[+-]?/ * Zero or more of preceding char /A.*B/ + One or more of preceding char /^\d+\s/

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-14

    Time Methods

    You can do various things with Time objects. Below is a sample program illustrating a Time object.

    timestuff.rb

    1. #!/usr/bin/ruby 2. d = Time.new # or Time.now 3. puts d.class 4. puts d

    The output from the program is shown below:.

    Time Sun Aug 15 09:57:48 -0400 2010 # UTC not GMT

    As a historical side, with modern precision instruments, the

    need for UTC was born. UTC stands for Coordinated Universal Time in English and

    Temps universel coordonn in French. The acronym was abbreviated UTC as a compromise

    between CUT and TUC in English and French, respectively.

    Here are some other useful Time methods. moretime.rb

    1. #!/usr/bin/ruby 2. t = Time.new 3. puts t 4. puts "DAY: #{t.day}" 5. puts "MON: #{t.month}" 6. puts "YR: #{t.year}" 7. puts "HR: #{t.hour}" 8. puts "MIN: #{t.min}" 9. puts "SEC: #{t.sec}" 10. puts "TOMORROW: #{Time.at(t + 60 * 60 * 24)}" 11. puts "USING CTIME: #{t.ctime}"

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-15

    Exercises 1. Write a program that prompts the user to enter the radius

    of a circle.

    Accept the user input into a variable. Compute the area of the circle whose radius was input.

    The formula for the area of a circle is pi times the square of the radius.

    Use 3.14159 for pi. 2. Write a program that prompts the user for a string and a

    number on separate lines.

    The program should print the string replicated by the number. For example, if the string is "sample" and the number is 3,

    then samplesamplesample should be printed. 3. Write a program that prompts the user for two numbers.

    The first number will be the base. The second number will be the exponent. Print the result of raising the base to the exponent.

    4. Write a program that accepts a string from the user.

    Print the following about the string. Print the length of the string. Print the first five characters of the string. Look for and print the result of calling the method in the

    String class that will convert the string to lower case.

  • RUBY PROGRAMMING CHAPTER 2: STANDARD RUBY DATA TYPES

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 2-16

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-1

    Chapter 3: Language Components

    1) The if Statement..................................................................................................... 3-2

    2) The Logical Operators............................................................................................. 3-3

    3) The case Construct ................................................................................................ 3-4

    4) Loops ......................................................................................................................... 3-5

    5) Iterators .................................................................................................................... 3-9

    6) Numeric Iterators................................................................................................... 3-10

    7) String Iterators....................................................................................................... 3-13

    8) Methods................................................................................................................... 3-16

    9) Odds and Ends ....................................................................................................... 3-18

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-2

    The if Statement

    Ruby has a rich set of control flow constructs, each of which typically uses a relational operator.

    Operator Meaning == Equal != Not equal > Greater than < Less than >= Greater than or equal to

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-3

    The Logical Operators

    There are many cases where a compound condition must be evaluated.

    This is where logical operators come into play. The table below lists these logical operators.

    Operator Meaning ! Logical NOT&& Logical AND|| Logical OR not Logical NOTand Logical ANDor Logical OR

    Below is a program that uses both the logical || operator and the elsif construction.

    elsif.rb

    1. #!/usr/bin/ruby 2. print "Enter a number: " 3. grade = gets.to_i 4. if grade < 0 || grade > 100 5. puts "ILLEGAL GRADE" 6. elsif grade < 60 7. puts "You got an F" 8. elsif grade < 70 9. puts "You got a D" 10. elsif grade < 80 11. puts "You got a C" 12. elsif grade < 90 13. puts "You got a B" 14. else 15. puts "You got an A" 16. end

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-4

    The case Construct

    Some decision making is coded more clearly if you use a case construction rather than a series of elsifs.

    case.rb

    1. #!/usr/bin/ruby 2. while true 3. print "Enter a number " 4. grade = gets 5. exit if grade =~ /exit|quit/i 6. case grade.to_i 7. when 90..100 8. puts "A" 9. when 80..89 10. puts "B" 11. when 70..79 12. puts "C" 13. when 60..69 14. puts "D" 15. when 0..59 16. puts "F" 17. else 18. puts "ILLEGAL" 19. end 20. end

    The output from the above program is shown below.

    Enter a number 85 B Enter a number 75 C Enter a number quit

    Notice that the above code also illustrates the following. Modifier form of the if statement Regular expressions

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-5

    Loops

    The Ruby language offers the usual set of traditional looping constructs, as well as some special looping constructs known as iterators.

    The example below demonstrates use of the traditional loops. loops.rb

    1. #!/usr/bin/ruby 2. print "For loop using inclusive range: " 3. for i in 0..10 4. print i, " " 5. end 6. 7. print "\nFor loop using exclusive range: " 8. for i in 0...10 9. print i, " " 10. end 11. 12. print "\nWhile loop: " 13. i = 0 14. while i < 10 15. print i , " " 16. i += 1 17. end 18. 19. print "\nUntil loop: " 20. i = 0 21. until i > 9 # executes if condition is false 22. print i , " " 23. i += 1 24. end 25. puts

    The output from the above program is shown below.

    For loop using inclusive range: 0 1 2 3 4 5 6 7 8 9 10 For loop using exclusive range: 0 1 2 3 4 5 6 7 8 9 While loop: 0 1 2 3 4 5 6 7 8 9 Until loop: 0 1 2 3 4 5 6 7 8 9

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-6

    Loops

    Loop control can be altered by using the following statements.

    break break out of the loop next perform the next iteration of this loop redo perform the same iteration again

    The following example demonstrates the use of the break statement within a for loop.

    Any looping construct could have been used, not just a for loop.

    The break at the first value of the variable i that, when squared, is greater than 500.

    break.rb

    1. #!/usr/bin/ruby 2. for i in 1..100 3. squared = i ** 2 4. if squared > 500 5. break 6. end 7. print "#{i}:#{squared} " 8. puts if i % 5 == 0 # modifier form of an if 9. end 10. puts

    The output from the above program is shown below.

    1:1 2:4 3:9 4:16 5:25 6:36 7:49 8:64 9:81 10:100 11:121 12:144 13:169 14:196 15:225 16:256 17:289 18:324 19:361 20:400 21:441 22:484

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-7

    Loops

    The following example demonstrates the use of the next statement within a while loop.

    next.rb

    1. #!/usr/bin/ruby 2. total = 0; 3. while true 4. print "Please enter an integer: " 5. text = gets.chomp 6. break if text =~ /^quit$/i 7. next if text =~ /\D/ #contains a non-digit 8. total += text.to_i 9. puts " Subtotal is #{total}" 10. end 11. puts "Total is:", total

    Sample output from the program is shown below.

    Please enter an integer: 10 Subtotal is 10 Please enter an integer: 20 Subtotal is 30 Please enter an integer: asdf Please enter an integer: 50 Subtotal is 80 Please enter an integer: quit Total is: 80

    Note that in addition to the next statement skipping input that is not all digits, it also includes a break statement to quit out of the loop.

    The example on the following page demonstrates the use of the redo statement.

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-8

    Loops redo.rb

    1. #!/usr/bin/ruby 2. mistakes = 0 3. for i in 1..5 4. if mistakes == 2 5. puts "Too many mistakes" 6. break 7. end 8. puts "Please type the number shown: #{i}" 9. value = gets.to_i 10. if value != i 11. mistakes += 1 12. redo 13. end 14. puts " #{i} of 5 complete" 15. end 16. puts "Congrats - no mistakes" if mistakes == 0

    Sample output from the program is shown below.

    Please type the number shown: 1 3 Please type the number shown: 1 1 1 of 5 complete Please type the number shown: 2 2 2 of 5 complete Please type the number shown: 3 4 Too many mistakes

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-9

    Iterators

    Ruby also has a large set of looping constructs called iterators.

    An iterator in Ruby is a method that can invoke a block of code repeatedly.

    Ruby allows both {} and do/end iterator blocks. When the body of the iterator consists of a single statement, the

    {} syntax is suggested.

    When the body of the iterator consists of multiple statements, the do/end syntax is preferred.

    Each value that is generated by the iterator can be referenced within the block of code by assigning it to a variable inside of vertical bars |variable_name|. The variable_name is an arbitrary name assigned to the

    generated value that can then be accessed by that variable name each time through the iterator.

    The next few pages will demonstrate iterators. The first three examples will be iterators called on Integer

    objects and consist of the times, upto, and step iterators.

    Next, there will be two more examples that are called on String objects and consist of the upto and each_line iterators.

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-10

    Numeric Iterators

    Below is an example of the times iterator that can be called on Integer objects.

    times.rb

    1. #!/usr/bin/ruby 2. 5.times { print "Hello " } 3. puts 4. 5. 5.times { |value| print "Hello#{value} " } 6. puts 7. 8. text = "a" 9. 5.times do 10. puts text 11. text += "a" 12. end 13. 14. 5.times do |val| 15. print val 16. print " squared is " 17. puts val**2 18. end

    The output from the above program is shown below.

    Hello Hello Hello Hello Hello Hello0 Hello1 Hello2 Hello3 Hello4 a aa aaa aaaa

    aaaaa

    0 squared is 0 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-11

    Numeric Iterators

    Below is an example of the upto iterator being called on Integer objects.

    upto_numeric.rb

    1. #!/usr/bin/ruby 2. 1.upto(5) { print "Hello " } 3. puts 4. 5. 5.upto(10) { |value| print "#{value} " } 6. puts 7. 8. text = "a" 9. 1.upto(5) do 10. puts text 11. text += "a" 12. end 13. 14. 2.upto(4) do |val| 15. print val 16. print " squared is " 17. puts val**2 18. end

    The output from the above program is shown below.

    Hello Hello Hello Hello Hello 5 6 7 8 9 10 a aa aaa aaaa

    aaaaa 2 squared is 4 3 squared is 9 4 squared is 16

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-12

    Numeric Iterators

    Below is an example of the step iterator being called on Integer objects.

    step.rb

    1. #!/usr/bin/ruby 2. 1.step(10) { |i| print i, " " } 3. puts 4. 5. 1.step(10,2) { |i| print i, " " } 6. puts 7. 8. 10.step(1,-1) { |i| print i, " " } 9. puts 10. 11. a = 10 12. b = 1 13. c = -2 14. a.step(b,c) do |value| 15. puts value 16. end

    The output from the above program is shown below.

    1 2 3 4 5 6 7 8 9 10 1 3 5 7 9 10 9 8 7 6 5 4 3 2 1 10 8 6 4 2

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-13

    String Iterators

    Below is an example of the upto iterator being called on String objects.

    The upto iterator for strings provides a way to generate other strings.

    upto_text.rb

    1. #!/usr/bin/ruby 2. chars = "" 3. 'a'.upto('z') { |val| chars += val} 4. puts chars 5. chars = "" 6. "0".upto("9") { |val| chars += val} 7. puts chars 8. chars = "" 9. counter = 1 10. "aa".upto("cc") do |val| 11. chars += val 12. chars += "\n" if counter % 13 == 0 13. counter += 1 14. end 15. puts chars

    The output from the above program is shown below.

    abcdefghijklmnopqrstuvwxyz 0123456789 aaabacadaeafagahaiajakalam anaoapaqarasatauavawaxayaz babbbcbdbebfbgbhbibjbkblbm bnbobpbqbrbsbtbubvbwbxbybz cacbcc

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-14

    String Iterators

    There may be occasions when a Ruby string contains many lines (i.e., many new line characters).

    The default string iterator can process such a string a line at a time.

    each_strings.rb

    1. #!/usr/bin/ruby 2. lines = "this\nis\na simple\r\nexample" 3. lines.each_line do | aLine | 4. aLine.chomp! 5. print aLine + " " 6. puts aLine.length 7. end 8. puts 9. 10. lines = "Hello" 11. lines.each_char do | aChar | 12. print aChar, "\t" 13. end 14. puts 15. 16. lines.each_byte do | aByte | 17. print aByte, "\t" 18. end 19. puts "\n\n" 20. 21. lines = "\u03C0" # Greek lowercase pi 22. lines.each_char do | aChar | 23. print aChar, " " 24. end 25. puts 26. 27. lines.each_byte do | aByte | 28. print aByte, " " 29. end 30. puts

    The output from the program is shown on the next page.

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-15

    String Iterators

    The output below was generated by the application on the previous page. this 4 is 2 a simple 8 example 7

    H e l l o 72 101 108 108 111

    207 128

    There are several things to note from the previous program. The lowercase pi character is a String of a single

    character. When iterated through using the each_byte iterator, it

    consisted of two bytes. The chop and chomp methods treat both a \n and \r\n as

    an end of line character that is removed.

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-16

    Methods

    In writing software, there is often the need to write the same logic and have it operate on different data.

    A sound strategy is to encapsulate the code and feed to it the data on which it will operate.

    Like other languages, this is accomplished in Ruby using methods.

    An example of such a method is shown next. largest.rb

    1. #!/usr/bin/ruby 2. def largest(a, b, c) 3. max = a > b ? a : b 4. max = c > max ? c : max 5. return max 6. end 7. print "input 3 numbers: " 8. a,b,c = gets.split 9. puts largest(a.to_i,b.to_i,c.to_i)

    The output from the above program is shown below.

    input 3 numbers: 3 2 10 10

    The keyword def defines a method. This is followed by the method name, which is followed by (if

    there are any) a set of parameters enclosed within parentheses.

    The parameters are comma-separated. The entire method is terminated with the keyword end.

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-17

    Methods

    Parameters are local. If they happen to coincide with the name of a variable outside

    the subroutine, they refer to different places in memory.

    Variables defined within a method are also local. The same named variables referenced outside of a method are

    references to different places in memory.

    The last evaluated expression within a function is the value returned by the function.

    Therefore, the previous function could have been written without a return statement.

    def largest(a, b, c) max = a > b ? a : b max = c > max ? c : max end

    A method can also have default parameters. If the programmer does not supply a parameter, the default

    value is used.

    default.rb

    1. #!/usr/bin/ruby 2. def total(first = 1, last = 10) 3. result = 0 4. first.upto(last) do | i | 5. result = result + i 6. end 7. result 8. end 9. puts total() # prints 55 10. puts total(5) # prints 45 11. puts total(10,20) # prints 165

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-18

    Odds and Ends

    You can execute command line commands within a Ruby script. (Be careful if not on a Unix variant!)

    datetime.rb

    1. #!/usr/bin/ruby 2. puts "DATE: " + `date | cut -c1-10` 3. puts "TIME: " + `date | cut -c12-16`

    The output from the above program is shown below.

    Date: Wed June 21 Time: 12:51

    You can also execute Ruby one-liners on the command line.

    For example, the following code displays the lines from file matching the pattern the.

    $ ruby -ne 'puts $_ if /the/' file

    When a control structure contains one line, you can write it using the modifier form.

    while true print "enter number or quit " line = gets.chomp exit if line == "quit" puts line.to_i * line.to_i end

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-19

    Odds and Ends

    There are various ways of assigning values. Variables are just references.

    x = "hello" y = x x[0] = 'M' puts y # prints Mello

    You can make multiple assignments.

    x = y = z = 0 You can make parallel assignments.

    a = 5 b = 10 c = 20 a,b,c = c,a,b puts a # 20 puts b # 5 puts c # 10

    Code can be executed when your program is being loaded by using a BEGIN block. Likewise, code can be executed after your program has terminated by using an END block.

    beginend.rb

    1. #!/usr/bin/ruby 2. BEGIN { 3. puts "BEGIN: " + Time.now.to_s 4. } 5. sleep 5 6. END { 7. puts "END: " + Time.now.to_s 8. }

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-20

    Odds and Ends

    Ruby allows the __END__ directive so that you can exclude, from execution, the bottom part of your program.

    Using this directive allows you to write large portions of code, while executing all but the last so many lines.

    end.rb

    1. #!/usr/bin/ruby 2. puts "line1" 3. puts "line2" 4. __END__ 5. puts "line3"

    The output from the above program is shown below.

    line1 line2

    You can place data below the __END__ line and have your program read it with the pre-opened object DATA.

    data.rb

    1. #!/usr/bin/ruby 2. line = DATA.gets # read one line 3. x = DATA.read # read rest of lines 4. puts "FIRST LINE: " + line 5. x.each_line { | x | puts x } 6. __END__ 7. Hello there, how are 8. you doing today?

    The output from the above program is shown below.

    FIRST LINE: Hello there, how are you doing today?

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-21

    Exercises 1. Write a program that inputs a number.

    The program should print the square of the number and whether the number is positive, negative, or zero.

    2. Write a program that inputs two numbers, one per line.

    The program should determine which number is larger or if they are the same.

    3. Write a program that prints out the numbers from zero to some higher limit (but only if the number is divisible by 7).

    The limit should be supplied interactively. 4. Write a program that reads five lines entered by the user

    and displays those lines that both begin with a capital letter and end with a lower case vowel.

    5. Write a program that loops over lines entered by the user.

    The program should print all those lines that represent .com domain names (i.e., www.trainingetc.com).

  • RUBY PROGRAMMING CHAPTER 3: LANGUAGE COMPONENTS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 3-22

    This Page Intentionally Left Blank

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-1

    Chapter 4: Collections

    1) Arrays........................................................................................................................ 4-2

    2) Array Operator Methods ........................................................................................ 4-5

    3) Array Equality Operator ........................................................................................ 4-9

    4) Arrays as Stacks and Queues................................................................................ 4-10

    5) Higher Dimensional Arrays .................................................................................. 4-11

    6) Other Useful Arrays Methods............................................................................... 4-12

    7) Command Line Arguments................................................................................... 4-13

    8) Hashes ..................................................................................................................... 4-14

    9) Common Hash Methods ........................................................................................ 4-17

    10) Sorting Hashes........................................................................................................ 4-18

    11) Iterators with Arrays and Hashes ........................................................................ 4-20

    12) Arrays and Methods .............................................................................................. 4-21

    13) Hashes and Methods.............................................................................................. 4-22

    14) Named Parameters................................................................................................. 4-23

    15) Symbols ................................................................................................................... 4-24

    16) Procs ........................................................................................................................ 4-26

    17) Closures................................................................................................................... 4-28

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-2

    Arrays

    This section builds on some of the rudimentary ideas covered in the previous chapter.

    We are mostly concerned here with two collection types, arrays and hashes.

    An array is an ordered set of values, each of which can be selected by using a subscript.

    The subscript essentially "measures" the distance from the beginning of where the array is stored in memory.

    (see negative subscripts later!)

    Arrays are dynamic, meaning their size may vary during the running of the program.

    Arrays can be created as shown below. values = [ 10, 20, 30 ] # create data = %W[ 5 10 15] # create print values # 102030 puts values.length # 3

    Elements can be accessed by using a subscript. Notice the first element in the array will have subscript zero. values[0] # 10 values[1] # 20 values[3] # nil values[-1] # 30

    You can add to an array as shown below. values[5] = 50

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-3

    Arrays

    Arrays are typically processed with loops. array_with_for_loop.rb

    1. #!/usr/bin/ruby 2. values = [ 10, 20, 30 ] 3. values[5] = 50 4. for value in values 5. print value, " " 6. end

    The output from the above program is shown below.

    10 20 30 nil nil 50

    You can also process an array by using the each method. The each method is another example of a Ruby iterator.

    The set of curly braces in the line below is called a block. values.each { |value| print value + " " }

    If the block contains more than one statement, you can use

    the do end sequence rather than the curly braces. ct = 0 values.each do |item| if item > 0 ct += 1 end end puts ct

    The variable inside the 'pipe' symbols obtains, in turn, each

    item in the array.

    Ruby arrays have a plethora of methods defined for them. You can create an array object and give its size and default

    values with the new method.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-4

    Arrays For example, the array data will have 10 items, each with a

    value of 0.

    vals = Array.new(10) # 10 items, each nil data = Array.new(10, 0) # 10 items, each 0 puts data.empty? # false puts data.length # 10

    Sometimes, it is necessary to create an empty array. mydata = Array.new puts mydata.empty? # true puts mydata.length # 0

    The join method is convenient for taking an array and creating a String from it.

    Each element in the resulting string is separated with your choice of a delimiter.

    This is useful when you need to print the elements of an array on a single line.

    printarray.rb

    1. #!/usr/bin/ruby 2. data = [ 10, 20, 30, 40 ] 3. print data 4. puts data 5. p data 6. puts data.join(" ")

    The output from the above program is shown below.

    1020304010 20 30 40 [10, 20, 30, 40] 10 20 30 40

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-5

    Array Operator Methods

    The Array class also defines many operator methods. We are referring here to operations on arrays, which are

    implemented as methods but can be invoked syntactically as operators.

    The first few of these operators are used to simulate (although not exactly) mathematical set operations.

    & set intersection | set union - set difference

    Below is an example demonstrating these operators. sets.rb

    1. #!/usr/bin/ruby 2. golf = %W[Bob Mike Joe Kevin Patti] 3. tennis = %W[Bob Patti Jason John] 4. puts "Golf: #{golf.join(' ')}" 5. puts "Tennis: #{tennis.join(' ')}" 6. both = tennis & golf 7. puts "Both (Intersection): #{both.join(' ')}" 8. players = tennis | golf 9. puts "All (Union): #{players.join(' ')}" 10. diff1 = tennis - golf 11. diff2 = golf - tennis 12. puts "Tennis - NOT Golf (Diff): #{diff1.join(' ')}" 13. puts "Golf - NOT Tennis (Diff): #{diff2.join(' ')}"

    The output from the above program is shown below.

    Golf: Bob Mike Joe Kevin Patti Tennis: Bob Patti Jason John Both (Intersection): Bob Patti All (Union): Bob Patti Jason John Mike Joe Kevin Tennis - NOT Golf (Diff): Jason John Golf - NOT Tennis (Diff): Mike Joe Kevin

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-6

    Array Operator Methods

    Some other array operators are shown below. *, +, [],

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-7

    Array Operator Methods

    The + operator simply concatenates two arrays. Since this is a simple operator, the example below melds other

    array methods as well.

    [ ] sort size, length

    concat.rb

    1. #!/usr/bin/ruby 2. teachers = %W[Dave alan Mike Barb] 3. sales = Array['bonnie', "sheri"] 4. susans = ['SusanD', 'SusanS', 'SusanL'] 5. others = %W[Marvin Charles] 6. staff = teachers + sales + others + susans 7. puts staff.length 8. puts staff.size 9. puts staff.sort

    The output from the above program is shown below.

    11 11 Barb Charles Dave Marvin Mike SusanD SusanL SusanS alan bonnie sheri

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-8

    Array Operator Methods

    The

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-9

    Array Equality Operator

    For arrays, the == operator tests to see whether respective elements of an array are equal.

    This method returns one of two Boolean values, true or false.

    Here is an example that exhaustively covers the possibilities.

    equal.rb

    1. #!/usr/bin/ruby 2. one = [1, 2, 3] 3. two = [1, 2, 3] 4. three = [1,2, 4] 5. four = [1, 2, 3, 4] 6. puts one == two 7. puts one == three 8. puts one == four 9. puts [] == []

    The output from the above program is shown below.

    true false false true

    The last line in the code above simply compares two empty

    arrays.

    The idea of two objects being equal is not a simple issue. At the heart of this matter is whether two object references are

    equal vs. the objects to which they refer.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-10

    Arrays as Stacks and Queues

    A stack is a data structure that allows for additions and deletions at the end.

    Stacks are widely used in many computer problems.

    You can use an array to implement a stack. The example below demonstrates several of the available

    methods.

    stack.rb

    1. #!/usr/bin/ruby 2. data = [] 3. puts "Push a few numbers onto an array." 4. 1.upto(5) { |number| data.push(rand(100) ) } 5. puts data 6. puts "Now pop a few of them off the array." 7. 1.upto(3) do |item| 8. puts data.pop 9. sleep(1) 10. end 11. puts data.size.to_s + " elements remain." 12. puts "Now clear the array" 13. data.clear 14. puts data.size.to_s + " elements now remain."

    There is no difference between

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-11

    Higher Dimensional Arrays

    Ruby does not support native two-dimensional arrays, but this is not a hazard.

    You can simply build an array of arrays. The example below demonstrates various techniques for

    looping through a multidimensional array. twodim.rb

    1. #!/usr/bin/ruby 2. a = [ [1, 2], [3, 4], [5, 6] ] 3. puts "Use an iterator." 4. a.each { | x | p x } 5. puts "Now use nested iterators." 6. a.each do |x| 7. x.each { |y| print "#{y} " } 8. puts 9. end 10. puts "Now use subscripts." 11. i = 0 12. while ( i < a.length ) 13. j = 0; 14. while ( j < a[i].length ) 15. print "#{a[i][j]} " 16. j += 1 17. end 18. puts 19. i += 1 20. end

    An array's flatten method can be used to extract all elements into a simple array.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-12

    Other Useful Arrays Methods

    Other useful array methods are shown below. array_others.rb

    1. #!/usr/bin/ruby 2. vals = [] 3. n = "\n" 4. 0.upto(10) {|i| vals[i] = rand(10)} 5. print "Values: ", vals.inspect, n 6. print "Unique Values: ", vals.uniq.inspect, n 7. print "Index of 4 from left: ", vals.index(4), n 8. print "Index of 4 from right: ", vals.rindex(4), n 9. print "Index NOT in the array: ", vals.index(30), n 10. print "Remove all occurrences of element: ", \ 11. vals.delete(4), n 12. print "Values after deletion: ", vals.inspect, n 13. print "Remove element from given index: ", \ 14. vals.delete_at(5), n 15. print "Values after deletion: ", vals.inspect, n 16. print "Insert into position 7 a value of 99: ", \ 17. vals.insert(7, 99).inspect, n 18. print "Values after insert: ", vals.inspect, n 19. print "Results of each_with_index:\n" 20. vals.each_with_index {|val, i| print "#{i}:#{val} "}

    The output from the above program is shown below. Values: [8, 0, 5, 7, 1, 3, 0, 0, 7, 6, 1] Unique Values: [8, 0, 5, 7, 1, 3, 6] Index of 4 from left: nil Index of 4 from right: nil Index NOT in the array: nil Remove all occurrences of element: nil Values after deletion: [8, 0, 5, 7, 1, 3, 0, 0, 7, 6, 1] Remove element from given index: 3 Values after deletion: [8, 0, 5, 7, 1, 0, 0, 7, 6, 1] Insert into position 7 a value of 99: [8, 0, 5, 7, 1, 0, 0, 99, 7, 6, 1] Values after insert: [8, 0, 5, 7, 1, 0, 0, 99, 7, 6, 1] Results of each_with_index: 0:8 1:0 2:5 3:7 4:1 5:0 6:0 7:99 8:7 9:6 10:1

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-13

    Command Line Arguments

    Ruby has a built-in array named ARGV, which represents the arguments passed to the command from the command line.

    This array does not include the command name.

    Below is a simple program that displays the sum of the integers between the two arguments given on the command line.

    sumfrom.rb

    1. #!/usr/bin/ruby 2. if ARGV.length != 2 3. puts "Usage sumfrom.rb low high" 4. exit 1 5. end 6. low = ARGV[0].to_i 7. high = ARGV[1].to_i 8. sum = 0 9. low.upto(high) { | i | sum += i } 10. puts sum

    The output from the above program is shown below.

    $ sumfrom.rb usage: sumfrom.rb low high $ sumfrom.rb 1 10 55 $ sumfrom.rb 10 20 165

    Most of the code above is self-explanatory. The strings from the command line need to be converted to

    integers in order to compute with them.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-14

    Hashes

    There are a many problems where software solutions involve paired data.

    Arrays are not sufficient to handle these particular problems.

    A hash solves this problem. A hash is a data structure of unordered pairs. Each pair consists of a key and a value. The key is used to fetch the value.

    A hash effectively saves you the cost of a lookup. The following example demonstrates the use of a hash.

    hash.rb

    1. #!/usr/bin/ruby 2. caps = { 3. "Maryland" => "Annapolis", 4. "Virginia" => "Richmond", 5. "New Jersey" => "Trenton", 6. "Massachusetts" => "Boston" 7. } 8. while true 9. print "Enter a State " 10. st = gets.chop 11. next if st.length == 0 12. break if st == "quit" 13. if caps.has_key?(st) 14. puts "#{caps[st]} is capitol of #{st}" 15. else 16. puts "No such state as #{st}." 17. end 18. end

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-15

    Hashes

    The code from the previous example is discussed below in detail.

    The code contains a hash of four pairs. The states are the keys and the capitols are the values. caps = { "Maryland" => "Annapolis", "Virginia" => "Richmond", "New Jersey" => "Trenton", "Massachusetts" => "Boston" }

    If the length of the text from the user is the empty string, the

    next iteration of the while loop will be executed.

    next if st.length == 0 If the length of the text was not the empty string it is then

    checked to see if the user wants to quit from the loop.

    break if st == "quit" Next, we see whether this particular key is in the hash.

    if caps.has_key?(st) puts "#{caps[st]} is capitol of #{st}" else puts "No such state as #{st}." end

    If the key is present, we display the value for that key.

    puts "#{caps[st]} is capitol of #{st}"

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-16

    Hashes

    Although the situation varies according to the problem, hashes are often built dynamically during the running of the program, rather than being initialized as in the previous program.

    In the program that follows, name value pairs are entered at the program prompt, read by the program, and stored in a hash.

    bank.rb

    1. #!/usr/bin/ruby 2. bank = Hash.new(0) 3. while true 4. print "Enter name and amount of deposit: " 5. line = gets.chop 6. name, deposit = line.split 7. break if name == "quit" 8. bank[name] += deposit.to_i 9. end 10. bank.each { |n, v| puts "#{n}\t#{v}" }

    Note that hash keys are unique, so in the following sequence, the value 10 will be printed.

    bank['mike'] += 3 bank['mike'] += 4 bank['mike'] += 3 puts bank['mike'] The program above splits each line into two fields and then

    adds the value in the second field to the value part of the pair whose key is given in the first field.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-17

    Common Hash Methods

    Here are the most common methods used in connection with hashes.

    Create an empty hash. caps = Hash.new

    Create an empty hash with a default value for unseen keys. caps = Hash.new("Empty")

    Access the keys. caps.each_key do | key | puts key end

    Access the values. caps.each_value { | value | puts value }

    Access the pairs. caps.each do | key, value | puts key + " => " + value end

    Delete a pair. caps.delete('Maryland')

    Get the keys. keys = caps.keys # array of keys

    Get the values. keys = caps.values # array of values

    Additionally, take note of clear and invert.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-18

    Sorting Hashes

    If you wanted to print just the keys in sorted order, the following would work.

    puts bank.keys.sort.join(" ")

    If you just wanted to see the values in sorted order, you could code the following.

    puts bank.values.sort.join(" ")

    If you wanted to sort the pairs by keys, then the following would work.

    puts score.sort.join(" ") Unlike sorting the keys and the values, this particular sort is on

    the hash itself.

    In this situation, the pairs are sorted on the keys, by default. However, in order to gain some insight into how that sort works,

    examine the following.

    score = { 'a' => 2, 'x' => 5, 'c' => 1 } score.sort.class # Array score.sort.size # 3 score.sort[0] # ['a', 2 ] score.sort[1] # ['c', 1 ]

    You can see that the hash sort method returns an array of as

    many two-element arrays as there were pairs in the hash.

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-19

    Sorting Hashes

    Each two-element array contains a name and a value pair. If you give the sort a block of code, you can compare whichever

    part of the two-element array that you wish.

    By default, the comparison is made on the keys. However, you can also compare on the values.

    score.sort { | a,b |a[1] b[1] } The comparison operator , also known as the spaceship

    operator, will be discussed in more detail in a later chapter.

    In any case, the variables a and b each represent an array of two elements.

    Each two-element pair represents a key and a value. In this case, we are comparing the values rather than the

    keys.

    If we had coded as shown below, then we would get the default behavior, shown on the previous page.

    score.sort { | a,b |a[0] b[0] }

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-20

    Iterators with Arrays and Hashes

    One of the strengths of the Ruby language lies within the many iterators that operate on collections.

    Below are a few array iterators that we have not yet seen. You can delete all the elements of an array for which a certain

    block of code is true.

    x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10] puts x.join(" ") y = x.delete_if { |item| item % 2 == 0 } puts y.join(" ") # 1 3 5 7 9

    You can collect all the elements of an array and perform some

    function on them.

    x = [ 1, 2, 3, 4, 10] z = x.collect { | elem | elem * 2 } puts z.join(" ") # 2 4 6 8 20

    Hashes also have some iterators defined. You can delete a pair if the following key, value pair is a match.

    score = Hash.new score['John'] = 80 score['Alice'] = 97 score['Tim'] = 73 score['Peter'] = 83 score['Jake'] = 79 y = score.delete_if {| key, val | key =~ /^J/ } puts y # Alice97Tim73Peter83

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-21

    Arrays and Methods

    It is common to have a method operate on an array. arrfun.rb

    1. #!/usr/bin/ruby 2. def subr(x) 3. sum = 0 4. for item in x 5. sum += item 6. end 7. sum 8. end 9. b = [5,6,7,8] 10. puts "TOTAL IS " + subr(b).to_s 11. a = [1,2,3,4,5,6,7,8] 12. puts "TOTAL IS " + subr(a).to_s 13. puts "TOTAL IS " + subr([1,2,3]).to_s

    The output from the above program is shown below.

    TOTAL IS 26 TOTAL IS 36 TOTAL IS 6

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-22

    Hashes and Methods

    Passing a hash to a method is also trivial. hash_total.rb

    1. #!/usr/bin/ruby 2. def hash_total(aHash) 3. sum = 0 4. aHash.values.each { | item | sum += item } 5. sum 6. end 7. score = { 'a' => 2, 'x'=> 5, 'c' => 1 } 8. puts hash_total (score) 9. puts hash_total ( 'a' => 2, 'x'=> 5, 'c' => 1 )

    If you need to send a simple value to a method, along with a hash, the hash parameter may be first or last.

    It is usually more convenient to pass the hash as the last argument.

    In this case, the {}'s are not necessary. hash_parameters.rb

    1. #!/usr/bin/ruby 2. def hashfirst(aHash, any) 3. puts aHash 4. puts "-----------" 5. puts any 6. puts "===========" 7. end 8. 9. def hashlast(any, aHash) 10. puts any 11. puts "-----------" 12. puts aHash 13. puts "===========" 14. end 15. 16. hashfirst({'a' => 2, 'x'=> 5, 'c' => 1}, 10) 17. hashlast(10, 'a' => 2, 'x'=> 5, 'c' => 1 ) 18. hashlast(10, {'a' => 2, 'x'=> 5, 'c' => 1} )

  • RUBY PROGRAMMING CHAPTER 4: COLLECTIONS

    2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 4-23

    Named Parameters

    When you use a method, you usually need to know the order in which you pass arguments.

    For example, if you were to write a method to raise a base to a power, you might proceed as follows.

    def myraise(base, power) base ** power end

    When users need to use this method, they need to know that

    the base is the first argument and the power is the second argument.

    Therefore, the first call below raises 2 to the 5th power but the second call raises 5 to the 2nd power. puts myraise(2,5) puts myraise(5,2)

    Using hashes, you can name the parameter. I