Wakatta!

Like Eureka!, only cooler

Seven Languages in Seven Weeks Ruby Day 1

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:

Hello, World
1
puts "Hello, world"

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:

Hello, World done wrong
1
print "Hello, world/n"

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:

Hello, Ruby
1
"Hello, Ruby".index("Ruby")

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:

Hello, many times
1
10.times { puts "Frederic" }

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:

Counting sentences
1
10.times { | i | puts "This is sentence number #{i+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:

Counting over range
1
(1..10).each { | i | puts "This is sentence number #{i}" }

Alternatively, I could build an enumerator using the upto method:

Counting over enumerator
1
1.upto(10) { | i | puts "This is sentence number #{i}" }

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.

Guessing Game (guess.rb) download
1
2
3
4
5
6
7
8
9
10
11
12
13
def play()
  target = rand(10)
  guess = -1
  while target != guess
    puts 'Guess a number'
    guess = gets().to_i
    puts 'too high' if target < guess
    puts 'too low' if target > guess
  end
  puts 'got it'
end

play()

And this wraps up day 1.

Comments