$var
is a global
@var
is an instance variable
@@var
is a class variable
name = 'Dr. Nick'
puts "Hi #{name}"
:left, :right, :up, :down
nil
is like
null
in Java
elsif
keyword for multiconditionals
irb> if 2 > 3
irb> puts "Hello"
irb> end
=> nil
irb> if 2 > 3
irb> puts "Hello"
irb> else
irb> puts "Goodbye"
irb> "World"
irb> end
Goodbye
=> "World"
irb> 2.even?()
true
irb> "Hello World!".split(' ')
["Hello", "World!"]
game.reset!
irb> 2.even?
true
irb> "Hello World!".split ' '
["Hello", "World!"]
def
keyword used to define methods
def fib(n)
if n < 2
return n
end
fib(n - 1) + fib(n - 2)
end
def fib(n, x1 = 0, x2 = 1)
return x1 if n == 0
return x2 if n == 1
fib(n - 1, x2, x1 + x2)
end
def method_with_options(takes_kittens: true, num_puppies: 3, max_puppy_size: 8)
...
end
def method_with_splats(*args, **kwargs)
...
end
10.times { |i| puts i }
10.times do |i|
puts i
end
Proc#call
to call a block
def times(n, &proc)
return if n == 0
proc.call n
times(n - 1, &proc)
end
lambda
irb> double = lambda { |x| x + x }
irb> double = ->(x) { x + x }
irb> double.call 2
4
irb> (0..2).each { |i| puts i }
0
1
2
irb> (0...2).each { |i| puts i }
0
1
irb> a = [1, 2, '3']
irb> a << 4
irb> a
[1, 2, '3', 4]
irb> a + [6, 7]
[1, 2, '3', 4, 6, 7]
map
,
filter
, and
reduce
are defined on arrays
irb> [0..2].map { |x| x * 2 }
[0, 2, 4]
irb> [0..2].filter { |x| x.even? }
[0, 2]
irb> [0...3].reduce(0) { |sum, elt| sum + elt }
6
for
loops in Ruby
each
method provides iteration
irb> ['cat', 'dog', 'mouse'].each { |animal| puts animal }
cat
dog
mouse
irb> { 'puppy' => Dog, 'kitten' => Cat, 'cub' => Bear }
irb> { :puppy => Dog, :kitten => Cat, cub: Bear }
irb> h = { :puppy => Dog, kitten: Cat, cub => Bear }
irb> h[:puppy]
Dog
irb> h[:puppy] = Wolf
irb> h[:puppy]
Wolf
map
,
filter
, and
reduce
are, of course, defined on hashes
irb> h.each { |key, value| ... }
irb> "abc def" =~ /a.c/
0
irb> "def abc" =~ /a.c/
4
irb> "abc def" =~ /adc/
nil