Saturday, February 16, 2013

7 Languages in 7 weeks: Ruby day 1

Having decided I spend far too much time programming with Java I added the 7 languages in 7 weeks to my Amazon wish list and come Christmas it turned up.

Day 1: Finding a Nanny (Ruby)

Firstly we're introduced to Ruby's interactive console. My first conclusion is that all languages should have an interactive console!

A few differences to Java that stand out:

  • Interpreted: Nuff said.
  • You have the unless conditional so you can write lines that read quite nicely: order.calculate_tax unless order.nil?
  • Everything is an Object, including primitives.
  • Duck typing: You can call any method on an object and if it has it at runtime it will be called. You don't have to have classes inherit from the same class to be used in the same way.

The homework

Print the string Hello, World.

puts 'hello, world'

For the string "Hello, Ruby" find the index of the word "Ruby"

irb(main):007:0> "Hello, Ruby!".index('Ruby')
=> 7

Print your name ten times

irb(main):009:0> for i in 1..10
irb(main):010:1> puts "Christopher"
irb(main):011:1> end

Print the string "This is sentence number 1" where the number 1 changes from 1 to 10

irb(main):009:0> for i in 1..10
irb(main):010:1> puts "This is sentence number #{i}"
irb(main):011:1> end

Run a Ruby program from a file

chbatey ~/dev/7languages/ruby $ cat day1.rb 
#!/usr/bin/env ruby

puts "Hello"

Bonus problem: Guess a number between one and ten:


#!/usr/bin/env ruby
rand = rand(10)
puts "A number between  0 and 9"
user = gets().to_i

if user < rand
  puts "Less"
elsif user > rand
  puts "More"
else
  puts "Equal equal!!"
end

puts "The number was #{rand}"

Well that's day one of Ruby done. I look forward to tomorrow!




No comments: