| layout | page |
|---|---|
| title | The basics |
Use the irb to try out the examples.
Don't forget to type!
print is similar to puts but it doesn't add a new line to the end of the output.
print "x + y ="
To read input from the console:
input = getsTo read input without the new line use chomp
input = gets.chomp###Ranges
A range is an interval with a beginning and an end.
To get the numbers between 1 until 5.
(1..5).to_aTo get all the numbers from 1 up to 5, excluding 5.
(1...5).to_a
to_areturns an array representation of an object. In the above case, it converts a range to an array
Random is an interface to a number generator. The rand() method takes in the max and returns an integer greater than zero and less than max. You can also use a range as a parameter.
Random.rand(5..10)In this exercise we'll create a small game to help us practise math.
Download the files to get started. If you are having any trouble you can get the files directly from Github.
To execute the file you must first change its permissions from the command line (to make it executable).
chmod a+x numbers.rband then run it
./numbers.rbIn this exercise we want to generate two random numbers x and y using Random.rand(). We will output the numbers to the console and read in the answer.
print "#{x} + #{y} = "
answer = gets.to_ito_i returns an integer representation of an object.
if the answer is correct, output Right!. If the answer is incorrect, output Wrong :(.
Use an if .. else .. statement
Now we also want to limit the generated number to be between 1 and 10. To do that, we can pass in a range as a parameter to Random.rand().
Let's add a loop, so that the game is repeated 10 times before it ends.
turns = 0
while turns < 10
turns = turns + 1
# game code
endWe can also store the number of correct and failed attempts so we can calculate the score of the game. We can do that by incrementing the value of a correct and wrong variables when we check if the answer is correct or not.
To calculate the percentage of correct answers we need to divide the correct answers with the total attempts and multiply the result by 100.
score = 100*...Output the score after the loop
puts "Rights #{correct}; Wrongs #{wrong}; Score #{score}%"To get the number of seconds that it takes to run the game we can store the timestamp at the beginning of the game and then subtract it at the end. To do that, we can use Time.now
Try outputting
Time.nowin the irb
First create and assign the time to a variable start. Then, subtract Time.now - start and output that.
puts "Total time #{duration} secondsYou can also calculate the average time it take to respond to each problem by dividing the duration with the amount of attempts.
puts "#{duration/turns} seconds per problem"At the beginning of the game ask for the number of turns. If return is pressed default to 0.
To dynamically load a value you can use the
||=operant.
# here the number will get assigned to 1 as its value is nil
number = nil
number ||= 1
# The number will not get assigned to 1 because it already has a value
number = 2
number ||= 1##Reading and writing to a file
In Ruby we can use the File object to read and write to files.
To open an existing file we use
File.open(filename, mode)The mode indicates if the file will be opened for reading or writing.
To write to a file, we must open it using the write mode (w), write the new content and close() it when we are done.
filename = "colors.txt"
file = File.open(fname, "w")
file.puts "red "
file.puts "green"
file.puts "blue"
file.closeAlternatively, we can use a block.
filename = "colors.txt"
File.open(filename, 'w') do |file|
file.write("red")
file.write("green")
file.write("blue")
endTo read from a file, we first open it and then while there is more content, read each line.
File.open('animals.txt', 'r') do |file|
while line = file.gets
puts line
end
endDownload the animals.txt file used in the example.
Now that we know how to store information, we can store and load the scores for our numbers game.
Extend the game to ask for the player's name at the end of the game, and store the name and time each game has taken in the scores.txt file using comma separated values
player1, 12.24
player2, 8.32
player3, 9.12
Then display the five highest scores.
To get the highest scores you can read in each line and then use split(",") to turn it into an array.
while entry = file.gets
scores << entry.split(",")
endYou can then use the array sort method.
Download and try to go through as much of the Ruby Koans as you can.
After you download the repository, you can generate the koans using
rake genTo regenerate and delete any progress you've already make run
rake regenTo try out the koans run rake. It gives you a hint as to what fails and you can move forward by fixing the file and running rake again.
If you are working through this at home you can ask for help in our gitter channel.
##Some reading material
Why's poignant guide to Ruby is a cartoon written about Ruby by a programmer called Why the Lucky Stiff. You can also download the pdf version.
This ends our Ruby basics tutorial. Is there something you don't understand? Try and go through the provided resources with your coach. If you have any feedback, or can think of ways to improve this tutorial send us an email and let us know.