Ruby review

Ruby REPL Read-Eval-Print-Loop

turn your cmd into ruby interactive

irb

TIP: last executed statement was saved in _ (underscore) variable

Scope

String

Symbols

Similar to enum in .NET

sim = :a_simple

Constant

CONSTANT_STARTS_WITH_UPPERCASE_LETTER = "A"
This_is_still_valid = true

Array

Regex

"Hello" =~ /e/ #=> 1 

Hash

.NET Dictionary

Methods

method name should be in convention

Class

Class accessor (attributes)

Inheritance

Modules

Think about namespace in .NET

  • Module cannot be instantiated
  • Cannot inherit or be derived from
  • Can contains classes, methods, attributes and sub modules

Conditional statement

Loop and iterator

built-in loop: for, while and until

lang = ["c#", "ruby", "js", "java"]

#for
for x in lang
  puts x
end

#while
@x = 5
while @x > 0
  @x -= 1
end

#until
until @x > 10
  @x += 1
end

Iterator: each, times, upto and downto

#each
lang.each do |x|
  puts x
end

#or
lang.each { |x| puts x }

#times
3.times do |x|
  puts "#{x} time"
end

Exception handling

begin
  x = 1 / 0
rescue ZeroDivisionError
  puts "Div by 0"
rescue Exception => e
  puts e.message
ensure
  puts "finally"
end

#raise exception
begin
  raise "throw an exception"
rescue
end

Define custom exception

class CustomException < StandardException
  attr_reader :msg

  def initialize(msg)
    @msg = msg
  end
end

raise CustomException.new("custom error")