Tuesday, May 14, 2013

Ruby Lesson 1 Section 2 of 4: String Methods

Section Topics:


  • .length 
  • .reverse
  • .upcase and .downcase 

So methods are like commands except for the following (that I know of): 
  1. A period is used before a method 
  2. You can have more than one method on a line and Ruby will follow the sequence from left to right

Remember in Ruby everything is case sensitive and just like with commands capitilizing any letter in a method will cause an error. 

So to explain what the 4 methods in this section does. 

.length returns the number of characters in string including numbers, letters, spaces, and symbols. 

Example: 
  1. Input: "David" .length

    Ouput: 5
  2. Input: "David ".length

    Ouput: 6

Note: Like setting variables the spaces between the method and string from the period does not affect the output. For instance ( "David"  .  length ) OR ("David".    length) will both give us an output of 5. 

.reverse returns the string backwards. 

Example:
  1. Input: "David" .reverse

    Ouput: "divaD"

. upcase capitalizes every letter in the string and .downcase lowercases every letter in the string. 

Examples:
  1. Input: "David" .upcase

    Ouput: DAVID
  2. Input: "David" .downcase

    Ouput: david

Extras 

Remember when I said methods can be on the same line as a command? And that Ruby will do them in order of left to right? Well I did some testing on matter.

Tests: 

  1. Input: print "david" .upcase

    Ouput: DAVID

    Lesson: Command and methods can exist on the same line.
  2. Input: print "david" .upcase.downcase

    Ouput: david

    Lesson: Ruby follows commands/methods from left to right
  3. Input: print "david" .upcase.downcase.length

    Ouput: 5

    Lesson: Same as test 2
  4. Input: print "david" .length.upcase.downcase

    Ouput: error: undefined method 'upcase' for 5

    Lesson: Same as test 2 and that the .upcase and .downcase methods will cause error for numbers
  5. Input: "david5" .upcase

    Ouput: DAVID5

    Lesson: Tested for .downcase and with symbols. .downcase and .upcase will work as long as there is a letter in the string.
  6. Input: "david".upcase print "hi"

    Ouput: error

    Lesson: Commands cannot be after methods
  7. Input: print "david".upcase
              print "david".upcase

    Ouput: DAVIDDAVID

    Input: puts "david".upcase
              puts "david".upcase

    Ouput: DAVID
                DAVID

    Lesson: Commands do not get overwritten by methods following it. This is an important one since all the other tests could have been concluded that the command was overwritten. 

No comments:

Post a Comment