Monday, February 27, 2012

Seven Languages in Seven Weeks - Ruby Day 1 Self-Study

I started reading Seven Languages in Seven Weeks. I'll be posting some of my answers to the self-study section at the end of each chapter, mainly for self-documentation.

Some links:

Print the string "Hello, world."
>> puts "Hello, World"
Hello, World
=> nil

For the string "Hello, Ruby", find the index of the word "Ruby"
>> "Hello, Ruby".index("Ruby")
=> 7

Print your name ten times
>> 10.times { puts "ant0inet" }
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
ant0inet
=> 10

Run a Ruby program from a file.
$ cat > hello_world.rb << EOF
> #!/usr/bin/env ruby
> puts "Hello, world."
> EOF
$ ruby hello_world.rb 
Hello, world.

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.
#!/usr/bin/env ruby

random_num = rand(10) + 1
puts "Enter your guess:"
guess = gets.to_i
until guess == random_num
  if guess < random_num
    puts "too low"
  else
    puts "too high"
  end
  guess = gets.to_i
end 
puts "correct"