The first day of the first language (Ruby) in Seven Languages in Seven Weeks, is fun and refreshing (especially after a long day with Java).
This is of course mostly due to the nature of Ruby, a language that is unapologetically designed to improve the programmer’s experience.
Basic types are introduced, as well as various looping and branching mechanisms.
Exercises
The exercises were painless, and the required code very short.
Print the string “Hello, world”
That should be easy enough. The simplest solution is to use puts
:
1
|
|
The difference between puts
and print
is that the former adds a new line, while the latter does not. So, a less natural way would be:
1
|
|
Finally, p
is used to inspect its argument, so it is not usable in this context: as the argument is a string, p
would print it enclosed with double quotes.
In “Hello, Ruby,” find the index of the word “Ruby.”
The index method on the String class is just what we need:
1
|
|
The index
method is actually more flexible, and regular expressions can be used as well.
Print your name ten times
The most natural way is to use the times from the Integer class:
1
|
|
This produces just what is needed. Alternatives will be looked at in the next exercise.
Print the string “This is sentence number i,” with i changing from 1 to 10
Once again, I could use the times
method:
1
|
|
The problem this time is that the range is from 0 to 9, so I have to add 1 to the variable before printing it.
Ranges can be used as well:
1
|
|
Alternatively, I could build an enumerator using the upto method:
1
|
|
In these last two the index variable ranges over the correct values.
I could then go over more basic looping constructs, like while
, but they really do not bring much here.
Bonus problem: Guessing game
Here, a basic looping construct like while
feels natural (at least to me). The code is fairly simple, there is no error checking on input, but hey, it’s just day 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
And this wraps up day 1.