introduction to ruby Flashcards
History of ruby:
What was ruby influenced by?
•It was also influenced by Eiffel and Lisp, Perl with Smalltalk-like features.
What is Ruby?
Ruby is a dynamic, reflective, general-purpose object-oriented programming language.
Ruby and Java Comparison
•Ruby
sleep 100
•Java
public class sleep{
public static void main (String[] args) throws InterruptedException {
Thread.sleep (100*1000);
}
}
Who was the designer of Ruby?
Ruby was first designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.”
The ruby language syntax is sensitive to the…
capitalization of identifiers, in all cases treating capitalized variables as constants.
•The sigils $ and @ do not indicate variable data type as in Perl, but rather….
function as scope resolution operators.
•One of ruby’s features is that it is thoroughly object-oriented with _____ , ______ , _______
inheritance mixins and metaclasses
What is Duck typing?
you don’t need a type in order to invoke an existing method on an object - if a method is defined on it, you can invoke it.
The name comes from the phrase “If it looks like a duck and quacks like a duck, it’s a duck”
What is Dynamic typing?
Dynamic typing just says that types are associated with run-time values, not with static variables and parameters.
Everything is an _________ (even statements) and everything is executed imperatively (even _________)
•Everything is an expression (even statements) and everything is executed imperatively (even declarations)
A ruby feature is that Succinct and flexible _____ that minimizes ______________ and serves as a foundation for _______________ languages.
Succinct and flexible syntax that minimizes syntactic noise and serves as a foundation for domain-specific languages
Ruby features: Dynamic _________ and ________ of objects to facilitate ______________
Dynamic reflection and alteration of objects to facilitate metaprogramming
Ruby features: ___________, _________ and _________, with a unique block syntax
•Lexical closures, iterators and generators, with a unique block syntax
Ruby feature: Literal notation for ______, ______, ________________ and _______
Literal notation for arrays, hashes, regular expressions and symbols
Ruby feature: •Embedding code in _______(interpolation)
Ruby feature: •Embedding code in strings (interpolation)
Ruby features: _______arguments
Default arguments
Ruby features: •________ collection
•Garbage collection
Ruby features: •Four levels of variable scope (_____, ______, __________, and ______) denoted by sigils or the lack thereof
•Four levels of variable scope (global, class, instance, and local) denoted by sigils or the lack thereof
Ruby features: Strict ________ rules (everything is _____except ____and ___)
Strict boolean coercion rules (everything is true except false and nil)
Ruby features: __________ continuations
First-class continuations
Ruby features: ________ handling
•Exception handling
Ruby features: ________ overloading
Operator overloading
Ruby features: Built-in support for ________numbers, ________ numbers and ________ arithmetic
Built-in support for rational numbers, complex numbers and arbitrary-precision arithmetic
Ruby features: Custom dispatch behavior (through : ________and : ________)
Ruby features: Custom dispatch behavior (through method_missing and const_missing)
Ruby features: Native ________ and cooperative ________ (________are 1.9/YARV feature)
•Native threads and cooperative fibers (fibers are 1.9/YARV feature)
Ruby features: Initial support for ________ and multiple character ________ (no ICU support)
•Initial support for Unicode and multiple character encodings (no ICU support)
Ruby features: ________on all major platforms
•Implemented on all major platforms
Ruby features:Native plug-in ____in __
•Native plug-in API in C
Ruby features:Large standard ________
•Large standard library
Ruby deviations:_________ evaluation of non-boolean data is strict: 0, “” and [] are all evaluated to true.
Boolean evaluation of non-boolean data is strict: 0, “” and [] are all evaluated to true.
–Only false and nil are FALSE
Ruby deviations: To denote a _________ without a decimal component, one must follow with a ________ (99.0) or an explicit conversion (____). It is ________ to append a dot (99.) since numbers are susceptible to _____ _____.
•To denote a floating point without a decimal component, one must follow with a zero digit (99.0) or an explicit conversion (99.to_f). It is insufficient to append a dot (99.) since numbers are susceptible to method syntax.
Variables always hold _________ to objects.
Variables always hold references to objects.
Ruby is object-oriented: every value is an ______, including classes and ________ of types that many other languages designate as ______ (such as integers, booleans, and “null”).
•Ruby is object-oriented: every value is an object, including classes and instances of types that many other languages designate as primitives (such as integers, booleans, and “null”).
Every function is a _____ and ______ are always called on an ______.
•Every function is a method and methods are always called on an object.
Ruby features: Centralized package management through ________
•Centralized package management through RubyGems
What are expressions in ruby?
•Expressions are Objects and return values
Methods defined at the top level _____ become members of the _____ class. Since this class is an ancestor of every other class, such methods can be called on any object.
•Methods defined at the top level scope become members of the Object class. Since this class is an ancestor of every other class, such methods can be called on any object.
Ruby outputs: All _______ also have an “inspect” method
–Includes list of _____ variables
•All Object’s also have an “inspect” method
–Includes list of instance variables
Ruby outputs: All Object’s have a “to_s” ______
And you probably want to define one for your _____
•All Object’s have a “to_s” method
–And you probably want to define one for your objects
Ruby methods: Has a “______” statement
Has a “return” statement
Ruby methods: Take ________
Take arguments
Ruby methods: Between “___” “___” pairs
•Between “def” “end” pairs
Ruby methods: But also returns last _________ ________
But also returns last expression evaluated
Creating and Extending Objects in Ruby
obj = Object.new
def obj.talk
puts “I am an object”
end
obj.talk
Objects have Identifiers
s1 = “Hello”
s2 = “Hello”
p s1.object_id
p s2.object_id
What does this output?
s1 = “Hello”
s2 = “Hello”
p s1.object_id
p s2.object_id
$ ruby ref.rb
70235101628760
70235101628740
Passing Parameters
obj = Object.new
def obj.c2f(c)
c * 9.0 / 5 + 32
end
p obj.c2f(100)
p obj.c2f 100
What does this output?
obj = Object.new
def obj.c2f(c)
c * 9.0 / 5 + 32
end
p obj.c2f(100)
p obj.c2f 100
$ ruby ref.rb
- 0
- 0
Optional Arguments
obj = Object.new
def obj.multi(*x)
p x
end
obj. multi()
obj. multi(1)
obj. multi(1,2,3)
What does this output?
obj = Object.new
def obj.multi(*x)
p x
end
obj. multi()
obj. multi(1)
obj. multi(1,2,3)
$ ruby ref.rb
[]
[1]
[1, 2, 3]
Ending Optional Arguments
obj = Object.new
def obj.optional(a,b,*c)
p a,b,c
end
obj. optional(1, 2)
obj. optional(1, 2, 3)
obj. optional(1, 2, 3, 4)
What does this code output?
obj = Object.new
def obj.optional(a,b,*c)
p a,b,c
end
obj. optional(1, 2)
obj. optional(1, 2, 3)
obj. optional(1, 2, 3, 4)
$ ruby ref.rb
1
2
[]
1
2
[3]
1
2
[3, 4]
Default Arguments
obj = Object.new
def obj.default(a,b=3)
p “#{a}, #{b}”
end
obj. default(1)
obj. default(1,4)
What is the output of this code?
obj = Object.new
def obj.default(a,b=3)
p “#{a}, #{b}”
end
obj. default(1)
obj. default(1,4)
$ ruby ref.rb
“1, 3”
“1, 4”
List Ruby variables
- Locals: start with lowercase or underscore
- Instance: start with ‘@’
- Class: start with ‘@@’
- Globals: start with ‘$’
- Constants begin with uppercase
Local Variables
•Locals: start with lowercase or underscore
Instance Variables
•Instance: start with ‘@’
Class Variables
•Class: start with ‘@@’
Global Variables
•Globals: start with ‘$’
Constant Variables
•Constants begin with uppercase
All Variables are References
•All Variables are References
–No base types as in other language (e.g. integer, float, string, etc.)
•Refer to Objects

All Variables are References
a = “Hello”
b = a
p a
p b
b = “Goodbye”
p a
p b
What does this output?
$ ruby ref.rb
“Hello”
“Hello”
“Hello”
“Goodbye”
Aliases
a = “Hello”
b = a
p a
p b
a.replace(“Yo”)
p a
p b
What does this output?
$ ruby ref.rb
“Hello”
“Hello”
“Yo”
“Yo”
Freeze Method
a = “Hello”
a. freeze
a. replace(“Yo”)
What will happen when we run this code?
$ ruby ref.rb
ref.rb:3:in `replace’: can’t modify frozen String (RuntimeError)
from ref.rb:3:in `<main>’</main>
Ruby Classes
- Class names are constants
- Define methods/messages
- Can reopen
- Can override
Override
class A
def m
“one”
end
def m
“two”
end
end
p A.new.m
What will this happen?
$ ruby ref.rb
“two”
Reopen
class A
def m
“one”
end
def m
“two”
end
end
p A.new.n
What will this code output?
$ ruby ref.rb
ref.rb:10:in <main>': undefined method
n’ for #<0x007f89f411cfd0> (NoMethodError)0x007f89f411cfd0></main>
Reopen
What will this code output?
$ ruby ref.rb
“two”
“three”
Initializers and Accessors
class B
def initialize(a, b)
@one = a
@two = b
end
def one
@one
end
def two
@two
end
end
b = B.new(1, 2)
p b.one
p b.two
What will this code output?
$ ruby ref.rb
1
2
Attribute Reader
class C
attr_reader :one, :two
def initialize(a,b)
@one = a
@two = b
end
end
c = C.new(3,4)
p c.one
p c.two
What will this output?
$ ruby ref.rb
3
4
Writing and Both methods
•attr_writer and attr_accessor
Ruby inheritance
•Single
–Like Java, unlike C++
•Receives all functionality from base (parent) class
–Can call base class function of the same name by “super”
- Adds specificity
- Modules
–“Mix ins”
Inheritance Code
class Human
attr_reader :personality, :income
def initialize(p, i)
@personality = p
@income = i
end
end
class Programmer < Human
def initialize(p, i)
super(p-100, i+100)
end
end
Superclasses
>> Programmer.superclass
=> Human
>> Programmer.superclass.superclass
=> Object
Class Variables and Methods
- Variables or methods where only one exists per class
- Every object of the class shares them
Class Variable
class Number
@@count = 0
def initialize(val)
@val = val
@@count = @@count + 1
end
def Number.count
@@count
end
end
a = Number.new(1)
b = Number.new(11)
c = Number.new(111)
p Number.count
What will this output?
$ ruby ref.rb
3
“Constant”
Z = 1
p Z
Z = 2
p Z
What will this output?
$ ruby ref.rb
1
ref. rb:3: warning: already initialized constant Z
ref. rb:1: warning: previous definition of Z was here
2
3 Ruby Constants concepts
- Constants defined within a class or module may be accessed anywhere within the class or module.
- Outside the class or module, they may be accessed using the scope operator, :: prefixed by an expression that returns the appropriate class or module.
- Constants defined outside any class or module may be accessed as it is or by using the scope operator with no prefix.
2 Ruby constants
- Constants may not be defined in methods.
- Constants may be added to existing classes and modules from the outside by using the class or module name and the scope operator before the constant name.
Class Methods
What will this output?
<0x007ffb3c84c940>0x007ffb3c84c940>
$ ruby ref.rb
main
C
C
Scope
class A p A::X
X=1 p A::B::X
class B p A::B::C::X
X=2
class C
X=3
end
end
end
What will this output?
$ ruby ref.rb
1
2
3
Inherited Class Variables
What will this output?
class Parent
@@age = 40
def age
@@age
end
end
class Child < Parent
@@age = 10
end
p Parent.new.age
$ ruby ref.rb
10
Private and Protected
What will this output?
$ ruby ref.rb
“yep”
“derived”
ref.rb:25:in <main>': private method
nope’ called for #<0x007fb869994408> (NoMethodError)0x007fb869994408></main>
Conditionals
- if/else/elsif/end
- if not (x ==1)
- if !(x==1)
- unless x==1/else/end
- puts x if x>0
- puts x unless x == 0
Allocation in Conditionals
if false
x = 1
end
p x
p y
What will this output?
$ ruby ref.rb
nil
ref.rb:5:in <main>': undefined local variable or method
y’ for main:Object (NameError)</main>
Assignment in Conditionals
if x = 1
p “Hi”
end
What will this output?
$ ruby ref.rb
ref.rb:1: warning: found = in conditional, should be ==
“Hi”
Operator Override
class Person
attr_reader :name, :age
def initialize(name,age)
@name = name
@age = age
end
def ==(other)
self.age == other.age
end
end
person1 = Person.new(“Alice”, 50)
person2 = Person.new(“Bob”, 50)
person3 = Person.new(“Alice”, 40)
p person1 == person2
p person1 == person3
What will this output?
$ ruby ref.rb
true
false
Case
a = “This”
case a
when “That”
p “I’m a that”
when “This”
p “I’m a this”
else
p “I’m neither”
end
What will this output?
$ ruby ref.rb
“I’m a this”
Override When’s “===“
class Person
attr_reader :name, :age
def initialize(name,age)
@name = name
@age = age
end
def ===(other)
self.age == other.age
end
end
person1 = Person.new(“Alice”, 50)
person2 = Person.new(“Bob”, 50)
def Person.compare(p1, p2)
print “#{p1.name} and #{p2.name}”
case p1
when p2
print “ are “
else
print “ aren’t “
end
print “the same\n”
end
Person.compare(person1, person2)
Person.compare(person1, person3)
What will this output?
$ ruby equal.rb
Alice and Bob are the same
Alice and Alice aren’t the same
Else in Case
5.times do |i|
case i
when 1
p “one”
when 2
p “two”
else
p i
end
end
What will this output?
0
“one”
“two”
3
4
Loops
n = 0
loop do
n = n + 1
puts n
break if n > 5
end
What will this output?
1
2
3
4
5
6
While
n = 0
while n < 5
n = n + 1
puts n
end
What will this output?
1
2
3
4
5
Begin/While
n = 0
begin
n = n + 1
puts n
end while n < 5
What will this output?
1
2
3
4
5
Until
n = 0
until n > 5
n = n + 1
puts n
end
What will this output?
1
2
3
4
5
6
Iterating on Lists
c=[“one”, “two”, “three”, “four”, “five”]
for i in c
puts i
end
What will this output?
$ ruby ref.rb
one
two
three
four
five
3 loop features
- Loops really just repeatedly execute code blocks
- I.e.: they are iterators
- Iterators repeatedly “yield” to code blocks
Code Blocks
- Defined inside “{}”or “do”
- Passed as parameters
- Called via “yield”
Blocks and Iterators
curlies when something is returned
puts [1,2,3].map {|n| n*10}
do when nothing is returned
[1,2,3].map do |n|
puts n*10
end
What will this output?
$ ruby ref.rb
10
20
30
10
20
30
my_times method
class Integer
def my_times
c = 0
while c < self
yield c
c += 1
end
self
end
end
a = 0.my_times {|i| p i}
puts “a = #{a}”
a = 5.my_times {|i| p i}
puts “a = #{a}”
a = -5.my_times {|i| p i}
puts “a = #{a}”
What will this output?
$ ruby ref.rb
a = 0
0
1
2
3
4
a = 5
a = -5
Exceptions
begin
a = 1 / 0
rescue ZeroDivisionError => e
puts e.message
puts e.backtrace
end
What will this output?
$ ruby ref.rb
divided by 0
ref. rb:2:in /'
ref. rb:2:in
<main>’</main>
Ruby Symbols
- Begin with ‘:’
- More similar to integers than strings
- Are immutable
- Are unique
- Used to refer to methods
- Often used in hashes
Symbol Example
p “abc”.object_id
p “abc”.object_id
p :abc.object_id
p :abc.object_id
What will this output?
$ ruby ref.rb
70190050355780
70190050355680
407688
407688
Numbers
•Numeric
–Float
–Integer
- Fixnum
- Bignum
Hashes
- Key/value pairs
- Use “{}” as literal
Hashing
hash = {
“red” => “ruby”,
“white” => “diamond”,
“green” => “emerald”
}
hash.each_with_index do
|(key,value),i|
puts “#{i} is #{key} => #{value}”
end
What will this output?
$ ruby ref.rb
0 is red => ruby
1 is white => diamond
2 is green => emerald
Older Symbol
hash = {
:red => “ruby”,
:white => “diamond”,
:green => “emerald”
}
Newer Symbol
hash = {
red: “ruby”,
white: “diamond”,
green: “emerald”
}
Array Initialization
>> Array.new(3)
=> [nil, nil, nil]
>> Array.new(3, “Hi”)
=> [“Hi”, “Hi”, “Hi”]
>> n = 0
=> 0
>> Array.new(3){n+=1; n*10}
=> [10, 20, 30]
More Array Initialization
>> a = Array.new(3, “Hi”)
=> [“Hi”, “Hi”, “Hi”]
>> a[0].object_id
=> 2189467100
>> a[1].object_id
=> 2189467100
>> a[2].object_id
=> 2189467100
>> a[0].replace(“Bye”)
=> “Bye”
>> a
=> [“Bye”, “Bye”, “Bye”]
Array Methods
a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
p a.flatten
p a.reverse
p [1, 2, 3, 3, 3, 4, 1].uniq
p [“2”, 1, 5, “3”, 4, “6”].sort_by {|a| a.to_i}
What will this output?
$ ruby ref.rb
[1, 2, 3, 4, 5, 6, 7, 8]
[[[5, 6], [7, 8]], [3, 4], 2, 1]
[1, 2, 3, 4]
[1, “2”, “3”, 4, 5, “6”]
Ranges
p (1..5).include?(5)
p (1…5).include?(5)
r = 1..10
p r.one? {|n| n == 5}
p r.any? {|n| n > 5}
p r.count {|n| n > 5}
p r.find_all {|n| n > 5}
What will this out?
$ ruby ref.rb
true
false
true
true
5
[6, 7, 8, 9, 10]
Global Regular Expression Print
misc=[75, “hello”, 10…20, “goodbye”]
p misc.grep(String)
p misc.grep(/o/)
p misc.grep(50..100)
p misc.grep(Fixnum)
p misc.grep(Integer)
What will this output?
$ ruby ref.rb
[“hello”, “goodbye”]
[“hello”, “goodbye”]
[75]
[75]
[75]
Each Takes an Array and a Block
[1,2,3].each {|i| puts “Received #{i}”}
$ ruby ref.rb
Received 1
Received 2
Received 3
Map
•Takes an array and returns an array
>> numbers = [“one”, “two”, “three”, “four”, “five”]
=> [“one”, “two”, “three”, “four”, “five”]
>> numbers.map {|number| number.capitalize}
=> [“One”, “Two”, “Three”, “Four”, “Five”]
Proc’s
- Ruby has first-class code blocks called “Proc”s
- Are a combination of code and context
- Proc’s can be assigned to variables, be array elements, etc., etc.
- Can be used for closures
Closure
def multiply_by(m)
Proc.new {|x| x * m}
end
p10 = multiply_by 10
p12 = multiply_by 12
p p10.call(10)
p p10.call(11)
p p12.call(1)
p p12.call(6)
What does this output?
$ ruby ref.rb
100
110
12
72
Another Closure
def make_counter
n = 0
Proc.new { n += 1 }
end
c1 = make_counter
c2 = make_counter
p c1.call
p c1.call
p c1.call
p c2.call
p c1.call
p c2.call
What does this ooutput?
$ ruby ref.rb
1
2
3
1
4
2
Ruby features: Interactive ________(a REPL (________/________/________)) – IRB
•Interactive Ruby Shell (a REPL (Read/Execute/Print Loop)) – IRB