Professional Documents
Culture Documents
Introduction to
Ruby
class Person
end
Person.class # => Class
Person.new.class # => Person
def double_it(input)
input * 2
end
double_it(1) # => 2
double_it("a") # => "aa"
class Person
attr_accessor :first_name, :last_name
attr_reader :person_id
alias :last_name, :family_name
end
Windows - RubyInstaller
puts greet
puts greet('everyone')
# >> Greetings, Sau Sheong!
# >> Greetings, everyone!
1 + 2 # => 3
1 + 2.1 # => 3.1
2**10 # => 1024
9 / 2 # => 4
5 % 3 # => 2
-3.abs # => 3
1.class # => Fixnum
(2**50).class # => Bignum
1.3.class # => Float
h = Hash.new # => {}
h['string'] = 1
h[:symbol] = 1
h # => {:symbol=>1, "string"=>1}
h.keys # => [:symbol, "string"]
h[:symbol] # => 1
for n in 0..2
puts n
end
(0..2).each do |n|
puts n
end
ary = [1,2,3]
ary.map {|n| n * 2} # => [2, 4, 6]
ary.select {|n| n % 2 == 0} # => [2]
ary.inject(0) {|sum, n| sum + n} # => 6
while condition
# ...
end
begin
raise StandardError.new("Oh, oh")
rescue RuntimeError
puts "runtime"
rescue StandardError
puts "standard"
end
# >> standard
File.open('test.txt','w') do |file|
file.write("line\n")
file.puts("line")
end
File.read('test.txt')
def initialize(factor=2)
@factor = factor
end
def multiply(value)
@factor * value
end
end
calc = Calc.new
calc.multiply 5 # => 10
calc.factor = 3
calc.multiply 5 # => 15
def bar
"bar"
end
end
class Fixnum
include Even
end