Script 1: Mile/Km conversion tool

#!/bin/ruby

#notice that this script uses 3 different kinds of commenting mechanisms. Can you spot all three?

#'puts' is like 'print' but also adds a newline
puts "convert from mile or km?"

#'gets' asks for input and saves it as a string in the local variable 'theScale'
theScale = gets
puts "how many?"

#'gets' still saves the user input as a string, even though they input a number
theNumber = gets

=begin
because 'theNumber' is a string and not an integer, we have to first convert 'theNumber' to an integer using '.to_i' in order to do math on it;
then we '.chomp' on the variable 'theScale' so we can test it for equivalence.
Without chomping, the string would have some extra bites on the end that would make our equivalence test fail
=end

theAnswer = (theNumber.to_i / 5.0 * 8) if theScale.chomp == "mile"
theAnswer = (theNumber.to_i / 8.0 * 5) if theScale.chomp == "km"

#this next line uses 'string interpolation' to insert the variable into the string. To insert variable, we use a '#' and enclose the variable name in curly braces
puts "The answer is #{theAnswer}"

#Challenge: can you figure out how to add the distance unit to the end
#so that it reads 'The answer is 100 Kms' or 'The answer is 100 miles'?
#You'll need a couple of those 'if' modifiers you saw earlier and an extra variable interpolated in the string.



See The Answer Here

Advertisement

Ruby Basics

As you saw in the ‘Hello Ruby World’ script, every script we write will start with

#!/bin/ruby

This isn’t actually part of the ruby language, but is a message to the shell environment telling it what sort of file it’s dealing with and where to find the ruby programme. Let’s move on to the basic syntactic structure of the ruby language itself.

Like many other languages, ruby uses ‘=’ to assign values to variables, and the double equals == to test evaluations. Try this script:

#!/bin/ruby
myAge = 46
puts
"You're 46, really?" if myAge == 46

Save it as ‘myAge.rb’ and type ‘ruby myAge.rb’ in Terminal. After verifying that it works, change the second occurrence of ’46’ to ’36’. Save the script and run it again in the Terminal. (Tip: you don’t need to keep typing the script name, just press the UP arrow while Terminal is active and it will fill in the previous command). Note that the script just silently fails because we didn’t tell it what to do if myAge didn’t evaluate to 46.

Let’s just look at that last line again (now corrected back to ’46’)

puts "You're 46, really?" if myAge == 46

This is one way to write a conditional test (ruby heads call this an ‘if modifier’). It’s fine if you have just a simple test, but with more conditions or code, you might want to use the block form:

#!/bin/ruby
myAge = 46
if myAge == 46 then
  puts
"You're 46, really?"
else
  puts
"You're not 46, you're 36!"
end

Run the script to check that it works. Now, change line 2 to myAge = 36, save and run again. You should now get the output

"You're not 46, you're 36!"

Ruby also uses something called ‘dot syntax’. Type and save the following script into your text editor, then run it in Terminal and examine the output. Be careful to type it exactly, noting that the word “gimme ” on line 2 has a space between the ‘e’ and the closing quotation mark, and that in the third line, the opening quotation mark is followed by a ‘\’, then an ‘n’ then the word ‘gimme’ with no spaces:

#!/bin/ruby
3.times {print
"gimme "}
puts
"\ngimme some more"

Hopefully what you see is:

gimme gimme gimme
gimme some more

Let’s just look at how that code works. Although the output is fairly simple, there’s a lot going on here. The second line isn’t, as you might expect, multiplying the number 3, but is actually calling a method .times, whose function is to repeat the code inside the following curly braces exactly the number of times specified by the preceding number. In short calling the method .times on a number n is the same as saying “repeat the following code n times”. Try changing the ‘3’ to another number and see the result. Inside the curly braces we have the command ‘print’, which does the same as ‘puts’ except that it does not move the cursor to a new line after outputting the string. In the final line of code, we start the quoted string with \n. This little character sequence tells the cursor to move to a new line BEFORE the script prints ‘gimme some more’. The cursor also moves to a new line AFTER the output of the string ‘gimme some more’ because we used the command ‘puts’. Try changing ‘puts’ to ‘print’ in the final line and observe the difference. Also notice that you could achieve the same effect as

puts "any old string"

with

print "any old string\n"

To sum up:

= is used to assign values
== is used to test values
. is used to call a method
{ } are used to enclose code
print is used to output a string
\n is used to move the cursor to a new line
puts is used to output a string and move the cursor to a new line at the end

Test Yourself!
Write a script that produces the following output (note you should ensure your script produces a space after the first line):

————————————

I say I say I say

I say
I say
I say

————————————-

See the Answer Here

NEXT >>

Getting Started

Ruby comes pre-installed on Macs. To verify and check the version you have, open the Terminal.app in your /Applications/Utilities folder and type

ruby -v

You should get back something like:

ruby 2.0.0p247 (2013-06-27 revision 41674) [universal.x86_64-darwin13]

Don’t worry if the version is not exactly the same as shown here, but you should be on at least ruby 2.0.

You can find out more about your ruby installation by typing

man ruby

at the Terminal prompt. Hit the space bar to scroll down and the 'U' key to scroll back up. Hit the 'Q' key to exit the man page.

You can use an interactive ruby shell to run ruby commands within Terminal by typing

irb

Use control-D on your keyboard to quit the ruby environment.

However, for the most part, we’ll be typing our scripts into their own files, then running the file from Terminal. To do this, you save the script with a .rb extension, then call it with the command ‘ruby’. Let’s have an example.

Open up a new document in a text editor (Text Edit will do, but you’d be far better off getting TextWrangler, TextMate or Tincta for coding work — they’re all free!). Type in the following:

#!/bin/ruby
puts "Hello Ruby World!"

Save the script as helloworld.rb in your home folder (it’s important that you save it directly in your home folder, not buried inside another folder). In Terminal, type:

ruby helloworld.rb

You should see the reply:

Hello Ruby World!

OK, we’ve confirmed your Ruby installation is working and that you know how to save and run a ruby script. 🙂

NEXT >>