9. Classes
irb(main):024:0> class Greeter
irb(main):025:1> def initialize(name = "World")
irb(main):026:2> @name = name
irb(main):027:2> end
irb(main):028:1> def say_hi
irb(main):029:2> puts "Hi #{@name}!"
irb(main):030:2> end
irb(main):031:1> def say_bye
irb(main):032:2> puts "Bye #{@name}, come back soon."
irb(main):033:2> end
irb(main):034:1> end
=> nil
10. Create an Object
irb(main):035:0> g = Greeter.new("Jins")
=> #<Greeter:0x16cac @name="JIns">
irb(main):036:0> g.say_hi
Hi Jins!
=> nil
irb(main):037:0> g.say_bye
Bye Jins, come back soon.
=> nil
11. Cycling and Looping
@names.each do |name|
puts "Hello #{name}!"
end
#C Code
for (i=0; i<number_of_elements; i++)
{
do_something_with(element[i]);
}
12. Ruby & PHP - Similarities
● Ruby is dynamically typed, like in PHP, so you don’t need to worry about having to
declare variables.
● There are classes, and you can control access to them like in PHP 5 (public, protected
and private)
● Some variables start with $, like in PHP (but not all)
● There’s eval, too.
● You can use string interpolating. Instead of doing ”$foo is a $bar”, you can do ”#{foo} is
a #{bar}”—like in PHP, this doesn’t apply for single-quoted strings.
● There’s heredocs
● Ruby has exceptions, like PHP 5
● There’s a fairly large standard library
● Arrays and hashes work like expected, if you exchange array() for { and }: array('a' =>
'b') becomes {'a' => 'b'}.
● true and false behave like in PHP, but null is called nil
13. Ruby & PHP - Differences
● There’s strong typing. You’ll need to call to_s, to_i etc. to convert between strings,
integers and so on, instead of relying on the language to do it
● Strings, numbers, arrays, hashes, etc. are objects. Instead of calling abs(-1) it’s -1.abs
● Parentheses are optional in method calls, except to clarify which parameters go to
which method calls
● Variables are references.
● There’s no abstract classes or interfaces
● Hashes and arrays are not interchangeable
● Only false and nil are false: 0, array() and "" are all true in conditionals.
● Almost everything is a method call, even raise (throw in PHP).