« Back to posts

Seven Languages: Week 1 (Ruby) - Day 1

27 Nov 2011

Out of the seven languages in this book, Ruby is the one I was most familiar with previously. It made for an easy start, and gave me a bit of momentum before I started to tackle languages like Prolog. I’m appreciative of that, because Prolog sure was a struggle for a while.

(This article is part of a series of posts I am doing about my journey through the exercises of the book Seven Languages In Seven Weeks. This article is the first one in the series. For an overview see the Seven Languages project page.)

Day 1 of Week 1 was pretty basic - a bit of string manipulation and looping. Ruby makes things like this very short and pretty.

For example, being able to repeat a string like: "Nick " * 10 or loop like: (1..10).each { |num| do_stuff(num) } is great.

Here is a nicely formatted version of my solutions to the exercises from Day 1 of Ruby. The home of the following code is on github with the other exercises.

Find:

1. A method that substitutes a part of a string
puts "BAM".gsub "M", "TMAN"
Output:
BATMAN

Do:

1. Print the string "Hello World"
puts "Hello World"
Output:
Hello World
2. For the string "Hello, Ruby," find the index of the word "Ruby."
# literally:
p "Hello, Ruby,".index "Ruby."
# realistically:
puts "Hello, Ruby".index "Ruby"
Output:
nil
7
3. Print your name ten times
puts "Nick " * 10
Output:
Nick Nick Nick Nick Nick Nick Nick Nick Nick Nick 
4. Print the string "This is sentence number 1," where the number 1 changes from 1 to 10
(1..10).each { |num| puts "This is sentence number #{num}" }
Output:
This is sentence number 1
This is sentence number 2
This is sentence number 3
This is sentence number 4
This is sentence number 5
This is sentence number 6
This is sentence number 7
This is sentence number 8
This is sentence number 9
This is sentence number 10
Bonus: Write a program that picks a random number. Let a player guess the number, telling the player whether the guess is too low or too high.
random_number = rand(1000) + 1
guess = 0

while guess != random_number do
    print "Pick a number between 1 and 1000: "
    guess = gets.to_i
    puts "Too low!" if guess < random_number
    puts "Too high!" if guess > random_number
end

puts "Got it! It was #{random_number}"
Output:
Pick a number between 1 and 1000: 500
Too high!
Pick a number between 1 and 1000: 250
Too high!
Pick a number between 1 and 1000: 125
Too low!
Pick a number between 1 and 1000: 192
Too high!
Pick a number between 1 and 1000: 158
Too high!
Pick a number between 1 and 1000: 141
Too high!
Pick a number between 1 and 1000: 133
Too high!
Pick a number between 1 and 1000: 129
Got it! It was 129

Next in this series: Day 2 of Ruby

blog comments powered by Disqus
Content by Nick Knowlson: Google+
rsstwitter