Seven Languages: Week 1 (Ruby) - Day 1
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:
puts "BAM".gsub "M", "TMAN"
BATMAN
Do:
puts "Hello World"
Hello World
# literally:
p "Hello, Ruby,".index "Ruby."
# realistically:
puts "Hello, Ruby".index "Ruby"
nil
7
puts "Nick " * 10
Nick Nick Nick Nick Nick Nick Nick Nick Nick Nick
(1..10).each { |num| puts "This is sentence number #{num}" }
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
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}"
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