As I said, Ruby is a language I know pretty well already, so this is a gentle introduction for me. Tate compares Ruby to Mary Poppins — magical and fun. I hated that film. But I take the point. The excercises are pretty trivial, but here are my answers.
helloworld.rb
Print the string "Hello, World."
Yay! Classic.
puts "Hello, World."
For the string "Hello, Ruby," find the index of the word "Ruby".
p "Hello, Ruby".index("Ruby")
times0.rb
Print your name 10 times
10.times {|i| p "Charlie"}
times1.rb
Print the sentence "This is sentence number 1" where 1 changes from 1 to 10
10.times {|i| p "This is sentence #{i+1}"}
numguess.rb
If you're feeling the need for a little more, 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.
A couple of things. I made a version that loops round so you can play again. The original spec doesn't specify that you should tell the player oif they guess correctly ( ;-) )! I’ve interpreted that as meaning that it counts as a 'win'. The %x{clear} is just a system call to the unix command "clear". I guess if you were using windows you'd do something with cls. Or print lots of empty lines.
#!/usr/bin/ruby
# Computer picks random number from 1..10
# User guesses
# Computer says higher, lower, etc.
clear = %x{clear}
guess='';
again=''
until again == 'q' || again == 'Q'
puts clear
print "Number guessing\n\n"
number = rand(10) + 1
puts "I am thinking of a number between 1 and 10. What do you think it is?"
while(1)
print "> "
guess = gets.to_i
if guess == 0
break
elsif guess==number
puts "You got it! Huzzah."
break
elsif guess < number
puts "Higher!"
else
puts "Lower!"
end
end
puts "Q to quit, anything else to continue"
again = gets.chomp!
end