To play with ruby in a system where it is installed, just type “irb”
Comments
=begin
Commenting out several lines (make sure =begin and =end are not indented)
=end
Strings and sub strings:
# Return a boolean base of substring found:
somestr.include? “somesubstr”
# Doing a search and replace regular expression (look for the letter y, change it to x):
somestring.gsub!(/y/, “x”)
“foo” + “bar” # String concatenation
“#{first_name} Hartl” # String variables interpolation
puts something # print variable something
mystr.empty? # Check if mystr is empty
nil.to_s # Will print “”, it cast to string
mystr.nil? # Test if mystr is null
puts “The string ‘#{string}’ is nonempty.” unless string.empty? // Print if not empty
"Toronto - Canada".downcase # Downcase stuff
"New York, USA".upcase # Upcase stuff
"HELLO".capitalize # Capitalize stuff
"a string".methods # If you want to see all other methods off the string class
"a string".methods.grep /case/ # even better, you can search them!
Playing with dates
'Now is #{Time.now}' // Prints the current machine's time
'Now is #{Time.now.year}' // Prints just the year part of the current time
if statements
if 1 < 2
print “I’m getting printed because one is less than two!”
elsif
print “something else”
else
print “the default”
end
# You can also use unless. If the expression is false (as oppose to true in if), the thing gets evaluated:
unless 1 > 2
print “This is an impossibility”
end
Methods in Ruby:
def string_message(string)
return “It’s an empty string!” if string.empty?
return “The string is nonempty.”
end
The return is implicit in the last line executed
Arrays:
a = “fooxbarxbazx”.split(‘x’) // Split into an array a using ‘x’, the opposite is a.join(‘x’)
a = [42, 8, 17]
a[-1] // Negative indexes start reading from the last element
a.first // First element, you can also use .second or .last
b = a.sort / a.reverse / a.shuffle // As their name indicate
a.sort! // this means apply the changes to a
(0..9).to_a // Produces an array with element from range 0 to 9. If you use three dots, the last number is not included
a = %w[foo bar baz quux] // Produces [“foo”,”baz”,”quux”]
a[0..1] // From the array above, produces a[“foo”, “baz”]
Blocks:
(1..5).each { |i| puts 2 * i } // Inputs 2, 4, 6, 8, 10
You can also have multi-line blocks:
(1..5).each do |number|
puts 2 * number
puts ‘–‘
end
each_with_index do |item, index| allows you to use the index inside the loop
3.times { puts “Betelgeuse!” } // Do something several times
a = (1..5).map { |i| i**2 } // Multipy numbers 1 to 5 to the power of two, and produce an array with the results
For loops:
for num in 1..20
puts num
end
Another kind of loop, with next and break statements:
i = 20 loop do
# Skipping odd numbers:
i -= 1 next if i % 2 == 0
print “#{i}”
break if i <= 0
end
Hashes:
user = { “first_name” => “Michael”, “last_name” => “Hartl” }
You can also use symbols, which are just strings with no quotes, to represent the above:
user = { :first_name => “Michael”, :last_name => “Hartl” }
user[:name] = user[“name”]
Printing hash values:
flash = { success: “It worked!”, error: “It failed.” }
flash.each do |key, value|
puts “Key #{key.inspect} has value #{value.inspect}”
end
The above will print:
Key :success has value “It worked!”
Key :error has value “It failed.”
Try / Catch statements in Ruby:
begin
# Something that may go wrong here
rescue Exception=>e
# Something did go wrong…
end
Getting user’s input:
gets.chomp
Accessing instances class variables (useful for testing):
my_instance = new SomeObject
my_instance
.instance_variable_get(:@some_variable)