Monday, June 27, 2016

Ruby Arrays

Need a reference text for the Ruby programming language? Get the Well-Grounded Rubyist.

You can use arrays to group similar data into a single entity, instead of having to create multiple variables just to separate that same kind of data. Ruby makes it really convenient for you to work with arrays: you can use bracket notation to access and set elements and use stack/queue-like methods to manipulate its data (i.e. push, pop, unshift, shift). Furthermore, you can easily go through an array and use that data in some form using iterators like each, map, select, and reject.

Creating an Array

You can either create an empty array or start it off with a few elements. To start off from scratch, you can use the [] empty array:

animals = []

Then, you would populate the array with elements using the operations we will learn later.

Otherwise, you can just initialize it with some elements:

animals = ["dog", "cat", "bear", "horse", "eagle"]

Arrays are denoted within brackets and have to be comma-separated. The array above is an array of strings and has 5 elements. Although we used strings above, you could use just about any data type because Ruby allows for arrays to have a mix of different types. For example, the following would be okay too:

array = [12, "dog", 3, "cat", 4.65, 0, "eagle"]

The above is an array of mixed data types -- it has integers, floats, and strings.

Accessing Elements

Coming back to our animals example, we can access each element using bracket notation:

animals = ["dog", "cat", "bear", "horse", "eagle"]

animals[0] is the first element of the array ("dog")
animals[4] is the last element of the array ("eagle")

To access elements in an array, you start counting from zero: so the first element will be at position 0 and the last element will be at position given by the size of the array MINUS one. In the case above, we have a 5-element array, so the position of the last element is 5 - 1, which is 4.

You can determine the size of the array in Ruby using the length or size method:

animals.size 
animals.length

They both return the same thing and will give you the number of elements in the array.

Modifying Array At the End

You can add new elements to the end of the array using the push method:

animals = ["dog", "cat", "bear", "horse", "eagle"]

animals.push("pigeon")

=> ["dog", "cat", "bear", "horse", "eagle", "pigeon"]

Note how the new element "pigeon" was added to the end of the array. This is like a stack for those of you familiar with basic data structures.

To remove an element from the end of the array, you can use pop:

animals = ["dog", "cat", "bear", "horse", "eagle"]

animals.pop
=> "eagle"

=> ["dog", "cat", "bear", "horse"]

Ruby gives you the popped element as the return value from the pop method, you can do something with that. The element is removed from the end of the array, though.

Modifying the Array At the Beginning

There are two other methods that allow you to add/remove elements from the beginning of the array instead of at the end: they are unshift and shift.

You can use unshift to add an element to the beginning of an array:

animals = ["dog", "cat", "bear", "horse", "eagle"]

animals.unshift("dinosaur")

=> ["dinosaur", "dog", "cat", "bear", "horse", "eagle"]

The new element has been added to the front of the array. This is like a queue for those of you familiar with basic data structures.

If you want to remove an element from the beginning of the array, use shift:

animals = ["dog", "cat", "bear", "horse", "eagle"]

animals.shift
=> "dog"

animals
=> ["cat", "bear", "horse", "eagle"]

When you do a shift operation, the element at the beginning of the array is removed and then returned to you so you can do something with it.

Modifying Specific Elements

You can use bracket notation to modify specific elements of an array at a certain index. For example, given the array of animals, you could replace the second element, "cat", with something else:

animals = ["dog", "cat", "bear", "horse", "eagle"]
animals[1] = "turtle"
animals
=> ["dog", "turtle", "bear", "horse", "eagle"]

Notice how the second element (whose index is 1) was replaced by "turtle."

Iterating Over Array

You can go through each element in the array using the each iterator. It is part of the Enumerable module. You can find many useful things there, so check it out. Anyway, here is an example:

animals = ["dog", "turtle", "bear", "horse", "eagle"]

animals.each { |animal| puts animal }

The above will go through each element in the array of animals and display its value (each on its own line). The each iterator accepts a block (denoted within braces) whose block parameter variable will take in each array element, one at a time, starting from the first one up to the last one, and then do something with it. In this case, I am using the puts statement to display each element's value.

Output:

dog
turtle
bear
horse
eagle

Other useful iterators are map, select, and reject. I invite you to look them up in the Ruby documentation. Now, let us see how to iterate over an array using a plain while loop:

animals = ["dog", "turtle", "bear", "horse", "eagle"]

index = 0

while index < animals.length
  puts animals[index]
  index += 1
end

The above uses the index variable to keep track of the location in the array. It starts off at 0 because the first element of the array is at position 0. Then, the loop condition is that the index is less than the number of elements in the array. Remember the last element is always the array size MINUS one. Inside the loop, you just display the value of the element at position index in the animals array. At the end of the loop, just before the end keyword, make sure to have the increment for index, so we do not end up with an infinite loop. The output of the above construct will be:

dog
turtle
bear
horse
eagle

Conclusion

Ruby makes it really nice and intuitive to work with arrays. You can think of them as stacks or queues, too. You can easily create, access, and modify its elements using Ruby's built-in methods. Furthermore, the Enumerable module has some interesting methods and iterators that allow you to extract certain pieces of information from Arrays. Don't forget to check that out as well! :) Thank you for reading and have fun! 

Looking for a reference text for Ruby? Get the Well-Grounded Rubyist.

Sunday, January 10, 2016

Ruby Basic String Methods

Need a reference text for the Ruby programming language? Get the Well-Grounded Rubyist.

This article will briefly go over Strings in Ruby.

First, let us talk about a few String methods. You can see all the methods available to a string if you call the "methods" method:

"Some String".methods

=> [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, 
:insert, :length, :size, :bytesize, :empty?, :=~, :match, :succ, 
:succ!, :next, :next!, :upto, :index, :rindex, :replace, :clear, 
:chr, :getbyte, :setbyte, :byteslice, :scrub, :scrub!, :freeze, 
:to_i, :to_f, :to_s, :to_str, :inspect, :dump, :upcase, :downcase, 
:capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, 
:hex, :oct, :split, :lines, :bytes, :chars, :codepoints, :reverse, 
:reverse!, :concat, :<<, :prepend, :crypt, :intern, :to_sym, :ord, 
:include?, :start_with?, :end_with?, :scan, :ljust, :rjust, :center, 
(output omitted)
:public_send, :respond_to?, :extend, :display, :method, :public_method, 
:singleton_method, :define_singleton_method, :object_id, :to_enum, 
:enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, 
:__id__]

There are many methods you could use, but here we will just talk about a few.

To start off, if you want to change the case of a string, you can either make it upper case or lower case with the following methods:

"Hello".upcase
"World".downcase

Output:

=> "HELLO"
=> "world"

There is a method that capitalizes the first character in the string and makes everything else lowercase:

"How ARe You dOIng toDAY?".capitalize

=> "How are you doing today?"

You can get rid of trailing spaces (either from the left or from the right) using the lstrip/rstrip method:

"   , And then ".lstrip

=> ", And then "

"   , And then ".rstrip

=> "   , And then"

Now, if you had those strings in a variable and you called all those methods, the original string would not change. That is, you would get a copy of the original string that was transformed according to the method you called. If you really want to change the original string, you would have to use the exclamation point, like this:

my_word = "Hello"
# Uppercases my_word permanently
my_word.upcase!
puts my_word

Output:

=> "HELLO"

Compare the use of no exclamation with one actually present:

sentence = "I climbed a tree."
another_sentence = sentence.upcase

puts "Original sentence: #{sentence}"
puts "Another sentence: #{another_sentence}"

sentence.upcase!
puts "Now sentence is: #{sentence}"

Output:

Original sentence: I climbed a tree.
Another sentence: I CLIMBED A TREE.
Now sentence is: I CLIMBED A TREE.

So in the code above we define a string variable and then create another string variable that takes the uppercase version of that original variable. Upon printing both of those variables, you see that the original is still unchanged while the second one has all its letters uppercase.

The code above uses string interpolation to display the value of a string variable. If you don't know about this, it is simple: within a double-quoted string, use #{} and place the variable name inside to actually display its value when you use puts. That is, puts "Something bla bla #{some_variable} will be displayed"

Now, moving on. The second part of the code calls the upcase method with a bang, !. Now, the actual variable will be modified. Whatever is stored in sentence will be turned into uppercase permanently. When you call puts to display the value of sentence, you see it is indeed a string with all characters uppercase.

Let us now talk about other more advanced methods. Before that, know that you can access any character in the string using standard array access notation:

my_string = "Somewhere over the rainbow"
# Displays the fourth character in the string (counts from 0)
puts my_string[3]

Output:

=> e

A useful method to search for a substring is the include? method.

"Welcome to my world".include? "world"
=> true

"Welcome to my world".include? "to"
=> true

"Welcome to my world".include? "earth"
=> false

So the method returns either true, if the sequence of characters was found in the string, or false, if the sequence of characters was not found.

The include? method can also take just a single character, if you use either "x", 'x', or ?x, where x is any character.

"Hello".include? 'e'
=> true

# Does it include the character e? (same as above)
"Hello".include? ?e
=> true
Now, another useful method is the sub method. You can substitute characters in a string with something else.

"I went to the gym today.".sub 'gym', 'theater'

Output (irb):

irb(main):023:0> "I went to the gym today.".sub 'gym', 'theater'
=> "I went to the theater today."

So the method sub substitutes a given string with a new string. Note that it does not change the original string, but makes a copy. If you want to actually change the original string (when working with variables), use the exclamation point:

sentence = "I ate pasta yesterday."
another_sentence = sentence.sub 'pasta', 'cake'

puts sentence
puts another_sentence

# Modify "sentence" variable permanently
sentence.sub! 'pasta', 'cake'
puts sentence

Output:

I ate pasta yesterday.
I ate cake yesterday.
I ate cake yesterday.

Note that the sub method substitutes only once. That is, the first match it finds will be the only one changed:

irb(main):002:0> sentence = "I love to eat a lot of pasta pasta much pasta"
=> "I love to eat a lot of pasta pasta much pasta"
irb(main):003:0> sentence
=> "I love to eat a lot of pasta pasta much pasta"
irb(main):004:0> sentence.sub 'pasta', 'pizza'
=> "I love to eat a lot of pizza pasta much pasta"
irb(main):005:0> sentence
=> "I love to eat a lot of pasta pasta much pasta"

That is all for this article. We talked about how you can modify strings using upcase, downcase, capitalize, as well as how to modify the original array using the exclamation (!) point. Then we looked at how to find matches in a string using include? and how to substitute matches with the sub method. There are many methods out there, so you could use the method "methods" to find out which methods are available to each class object.

Looking for a reference text for Ruby? Get the Well-Grounded Rubyist.

Sunday, January 3, 2016

Basic File I/O in Ruby

Need a reference text for the Ruby programming language? Get the Well-Grounded Rubyist.

Reading data from a file as well as writing data to a file has been made easy with Ruby. This article will cover how to read from a file and how to write to a file using Ruby's File class.

Let us jump right into it: to read each line from a file, use a block for the foreach() method of the File class.

File.foreach('somefile.txt') do |line|
  puts line
end

Each line will contain a \n newline character, so if you would like to chop it off, use

line.chomp

Assuming somefile.txt contains the following contents:

This is a sample file
With some contents within
This is the last line :)

The output of the Ruby script would be:

$ ruby basic_file_io.rb
This is a sample file
With some contents within
This is the last line :)

So you iterate through each line of the file and do something with that line. Specify the filename as the method parameter and then do a block with a parameter that will be used to hold each line, |line|.

There is one problem with the above construct: what if the file did not exist? Then surely you will get a problem:

basic_file_io.rb:1:in `foreach': No such file or directory - doesnt_exist.txt (Errno::ENOENT)

I tried to open a file called "doest_exist.txt" to read, but it did not exist, so I got an error.

To get around that error, you can either: handle the exception, or first check if the file exists before trying to do anything with it.

The following code illustrates how to handle exceptions:

begin
  File.foreach('doesnt_exist.txt') do |line|
    puts line
  end

rescue Exception => e
  puts "Oh no, something went terribly wrong!"
  puts e.message
  puts "Maybe we can do something about that problem here . . ."
end

Output:

$ ruby basic_file_io.rb
Oh no, something went terribly wrong!
No such file or directory - doesnt_exist.txt
Maybe we can do something about that problem here . . .

As you can see, you could have done something about the problem using the exception construct. You start off by saying "begin" then put everything you are attempting to do right afterward. Then, you make a "rescue" section with an object to hold the data for the exception; I used the name "e" above. Within the rescue section, you can determine how the program should behave in case some problem happens. Using e.message, you can also see the description of the problem. Finally, don't forget to finish everything with an "end."

Another way to handle problems when trying to read a file is using the "exist?" method. If you don't want to use exceptions, then you can try this out:

if File.exist? 'sample.txt'
  File.foreach('sample.txt') do |line|
    puts line.chomp
  end
else
  puts "I am sorry, but the file does not exist."
end

Assuming sample.txt does not exist, the output is:

I am sorry, but the file does not exist.

Now, let us see how to write to a file. In a similar fashion, we use the File class and call the open() method with a block that will do something to the file:

File.open('newfile.txt', 'w') do |file|
  file.puts "Hello everyone!"
  file.puts "This will be a brand new file!"
  file.puts "Just one more last line"
end

The above will open the file "newfile.txt" for "write." That is, a new file will be created and IF there is already a file named "newfile.txt," it will be completely wiped out and OVERWRITTEN. So be careful with the "w" mode. :) Moving on, you just use the |file| parameter to add things to the file. Just call file.puts with whatever string you want to add to the file contents. Because "puts" adds a newline character, each of those sentences written in the code above will be in their own line. When you take a look at the file, you get this:

$ cat newfile.txt
Hello everyone!
This will be a brand new file!
Just one more last line

Pretty cool, isn't it? Now, there are other modes that let you append to files, etc. I will leave it to you to Google it and find out about them if you don't already know. Here is a big hint: http://stackoverflow.com/questions/3682359/what-are-the-ruby-file-open-modes-and-options

And to conclude everything, just an important note: files are automatically *closed* at the end of each block, so there is no need to call a method to close the file, like in other programming languages such as C++ and PHP.

In summary, Ruby lets you handle file I/O with the File class. You can iterate over a file to read each line using the File.foreach() method. There might be cases in which the file will not exist, so you can handle issues with an exception (begin-rescue-end construct). There is also the option to use the File.exist? method to check whether a file exists. Writing to files can be done using the File.open() method in combination with a block with instructions to add something to the file. You can use the puts method on the block parameter to add some content to the file.

Looking for a reference text for Ruby? Get the Well-Grounded Rubyist.

Tuesday, December 1, 2015

The Switch Statement (Case)

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

The switch statement is similar to the if statement in a way that it determines what the program should do depending on certain conditions. It can also be used to control the flow of program. But the way it is built follows a different approach and, unlike the if statement, the switch statement allows for multiple cases or tests to yield the same outcome.

switch (myVariable)
{
    case myFirstCaseValue:
        // do these statements
        break;

    case mySecondCaseValue:
        // do these statements
        break;

    // and so on ...

    case myLastCaseValue:
        // do these statements
        break;

    default:
        // do these statements if no cases were matched (i.e. default behavior)
}

The way the switch traditionally works is like this: you give it an integer expression within the parenthesis (usually a variable). Then the program starts checking for each case that matches that particular case value with the value that was given to the switch statement. If the value of the case matches (that is, is equal to) the same value as the given integer expression in the parenthesis, then it will execute those statements under the case and will ONLY stop when it finds a break statement. The presence of the break is crucial for your switch statement to stop and yield proper behavior, so do not forget to include a break after listing all the statements that should be executed for each case.

Some programming languages other than C++ allow for the expression under switch (expression) to be something other than an integer value. PHP, for instance, allows the use of strings as the argument for the switch statement. With that, your cases can be string values instead of just integer values.

int myIntegerVariable;

myIntegerVariable = 3;

switch (myIntegerVariable)
{
case 1:
  cout << "Action #1" << endl;
  break;

case 2:
  cout << "Action #2" << endl;
  break;

case 3:
  cout << "Action #3" << endl;
  break;

default:
  cout << "Default Action" << endl;

}

Output:

Action #3

First we declare an integer value. Then we assign the value 3 to the integer variable. Next, the switch takes the integer value as its expression and then starts going through the cases. First, it checks the first case: does myIntegerVariable hold the value 1? No, because myIntegerVariable holds the integer 3. It then skips to the next case: does myIntegerVariable hold the value 2? No. Then, the next case: does myIntegerVariable hold the value 3? Yes. Because the values matched, the statements under "case 3:" are executed: it simply displays a message, "Action #3." The program will continue executing statements as long as there is no break statement, so we have to make sure there is a break so the switch statement is terminated and the program goes on to do other stuff.

Had we made the integer variable in the above example hold a case that is not 1, 2, nor 3, then it would default to the default case, which appears at the end, right before the closing brace. In a way, that is like the "else" of an if statement, when all the conditions have failed to be true.

Keep in the mind that the expression given to the switch statement, in C++, has to be an integer, and that the values for the "case X" have to be constant values (no variables allowed!). However, programming languages like PHP allow for the use of strings for the switch expression and cases.

As an example, the following would not work in C++:

string myGreeting;

myGreeting = "Hello";

switch (myGreeting)
{
case "Morning":
  cout << "Good morning to you, too!" << endl;
  break;

case "Hello":
  cout << "Hello, dolly!" << endl;
  break;

case "Night:":
  cout << "See you" << endl;
  break;

default:
  cout << "Good night!!" << endl;

}

Output (the compiler produces an error as output):

switch_statement.cpp: In function ‘int main()’:
switch_statement.cpp:87:21: error: switch quantity not an integer
   switch (myGreeting)

But the above construct would surely work in PHP because it allows strings to be used as the switch expression and case, unlike C++, which only allows integers to be used:

<?php

$myGreeting = "Hello";

switch ($myGreeting) {

  case "Morning":
    echo "Good morning to you, too!";
    break;

  case "Hello":
    echo "Hello, dolly!";
    break;

  case "Night":
    echo "Good night!!";
    break;

  default:
    echo "What's up?";

}

?>

Output:

Hello, dolly!

Switch expressions are typically given an enumeration ("enum") because it makes it easier to understand each case. An enum is like a label given to an integer. It looks like text, but is just a mask behind an actual integer number. For instance, you could make a list of enums that would give represent the integer values 0, 1, 2, 3 like this, using C++:

enum
{
    MY_FIRST_ENUM,
    MY_SECOND_ENUM,
    MY_THIRD_ENUM,
    MY_FOURTH_ENUM
};

With the above, you could use any of the enum items in place of a variable name or value. That would just mask the value behind the scenes. Had we used MY_THIRD_ENUM, we would be actually referring to the value 2 (you start counting from 0 if you use the above enumeration).

Imagine we have a game in which we are checking input from the user. Assume the user presses a key in the keyboard to move the character in the game. It would be either the up, down, left, or right arrows -- there are four cases. So we could make a switch statement to take care of that. But suppose we do not want to explicitly use integers for each case part. Instead, we could use an enum to mask those numbers and make us better understand the code we are writing:

// An enumeration for the keyboard keys
// Each gets associated with an integer value, starting from 0 going to 1, 2, 3, etc.
enum
{
    KEY_UP,
    KEY_DOWN,
    KEY_LEFT,
    KEY_RIGHT
}

// Assume we got the integer value associated with
// the key press inside userKeyPress
switch (userKeyPress)
{
    case KEY_UP:
        // move up
        break;

    case KEY_DOWN;
        // move down
        break;

    case KEY_LEFT:
        // move left
        break;

    case KEY_RIGHT:
        // move right
        break;
}

The above code would translate to exactly the code below. Which one is better to understand? I think the above code is much more intuitive.

// Assume we got the integer value associated with
// the key press inside userKeyPress:
// 0 means up key was pressed
// 1 means up key was pressed
// 2 means up key was pressed
// 3 means up key was pressed

switch (userKeyPress)
{
    case 0:
        // move up
        break;

    case 1;
        // move down
        break;

    case 2:
        // move left
        break;

    case 3:
        // move right
        break;
}

To conclude this article, let us touch upon making multiple cases yield the same outcome. Remember that we had the break statement for every case ending? What if we take that out and stack cases on top of each other, all leading to the same statements? That will do exactly what you would expect: If any of those cases matched, then it would execute those very statements!

Take a look at the code below. Imagine you took some test or a class and you got your grade inside a variable called myGrade. The example below uses a character to check each case. But wait, how come a character can be used if C++ only accepts integer as the expression/case for a switch? Well, that is because a character is actually an integer value. A character is just a mask for an integer value. For instance, the character 'A' can be a representation for the value 65. So the example below will work.

char myGrade = 'C';

switch (myGrade)
{
    case 'A':
        cout << "Excellent!" << endl;
        break;

    case 'B':
        cout << "Great!" << endl;
        break;

    case 'C':
    case 'D':
        cout << "Okay..." << endl;
        break;

    case 'F':
        cout << "You totally failed!" << endl;
        break;

    default:
        cout << "Invalid grade." << endl;
}

Output:

Okay...

The example checks for your grade and goes through each case. Observe we stacked case 'C' and 'D' on top of each other. That is because we want to display the same message if you got either grade C or D. So two cases are yielding the same outcome -- the same message. You can stack as many cases as you want. The secret to this is that once a case is matched, the program keeps executing statements as long as there is no break. Had the case been 'C' in the above example, then it would match there and everything below "case 'C':" would get executed up to the point where a break command was found, signaling the switch operation to terminate. That is, it will walk over to case 'D' and execute the cout with the message "Okay..." even though that case did not match.

Learning the C++ programming language? How about doing it with One Hour a Day.