introduction to ruby Flashcards

1
Q

History of ruby:
What was ruby influenced by?

A

•It was also influenced by Eiffel and Lisp, Perl with Smalltalk-like features.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Ruby?​

A

Ruby is a dynamic, reflective, general-purpose object-oriented programming language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Ruby and Java Comparison

A

•Ruby

sleep 100

•Java

public class sleep{

public static void main (String[] args) throws InterruptedException {

Thread.sleep (100*1000);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Who was the designer of Ruby?

A

Ruby was first designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

The ruby language syntax is sensitive to the…

A

capitalization of identifiers, in all cases treating capitalized variables as constants.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

•The sigils $ and @ do not indicate variable data type as in Perl, but rather….

A

function as scope resolution operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

•One of ruby’s features is that it is thoroughly object-oriented with _____ , ______ , _______

A

inheritance mixins and metaclasses

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Duck typing?

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Dynamic typing?

A

Dynamic typing just says that types are associated with run-time values, not with static variables and parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Everything is an _________ (even statements) and everything is executed imperatively (even _________)

A

•Everything is an expression (even statements) and everything is executed imperatively (even declarations)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

A ruby feature is that Succinct and flexible _____ that minimizes ______________ and serves as a foundation for _______________ languages.

A

Succinct and flexible syntax that minimizes syntactic noise and serves as a foundation for domain-specific languages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Ruby features: Dynamic _________ and ________ of objects to facilitate ______________

A

Dynamic reflection and alteration of objects to facilitate metaprogramming

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Ruby features: ___________, _________ and _________, with a unique block syntax

A

Lexical closures, iterators and generators, with a unique block syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Ruby feature: Literal notation for ______, ______, ________________ and _______

A

Literal notation for arrays, hashes, regular expressions and symbols

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Ruby feature: •Embedding code in _______(interpolation)

A

Ruby feature: •Embedding code in strings (interpolation)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Ruby features: _______arguments

A

Default arguments

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Ruby features: •________ collection

A

Garbage collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Ruby features: •Four levels of variable scope (_____, ______, __________, and ______) denoted by sigils or the lack thereof

A

•Four levels of variable scope (global, class, instance, and local) denoted by sigils or the lack thereof

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Ruby features: Strict ________ rules (everything is _____except ____and ___)

A

Strict boolean coercion rules (everything is true except false and nil)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Ruby features: __________ continuations

A

First-class continuations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Ruby features: ________ handling

A

Exception handling

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Ruby features: ________ overloading

A

Operator overloading

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Ruby features: Built-in support for ________numbers, ________ numbers and ________ arithmetic

A

Built-in support for rational numbers, complex numbers and arbitrary-precision arithmetic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Ruby features: Custom dispatch behavior (through : ________and : ________)

A

Ruby features: Custom dispatch behavior (through method_missing and const_missing)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Ruby features: Native ________ and cooperative ________ (\_\_\_\_\_\_\_\_are 1.9/YARV feature)
•Native **threads** and cooperative **fibers** (**fibers** are 1.9/YARV feature)
26
Ruby features: Initial support for ________ and multiple character ________ (no ICU support)
•Initial support for **Unicode** and multiple character **encodings** (no ICU support)
27
Ruby features: \_\_\_\_\_\_\_\_on all major platforms
•**Implemented** on all major platforms
28
Ruby features:Native plug-in \_\_\_\_in \_\_
•Native plug-in **API** in **C**
29
Ruby features:**Large standard** \_\_\_\_\_\_\_\_
•Large **standard library**
30
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
31
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**.
32
Variables always hold _________ to objects.
Variables always hold **references** to objects.
33
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").
34
Every function is a _____ and ______ are always called on an \_\_\_\_\_\_.
•Every function is a **method** and **methods** are always called on an **object**.
35
Ruby features: Centralized package management through \_\_\_\_\_\_\_\_
•Centralized package management through **RubyGems**
36
**What are expressions in ruby?**
•Expressions are Objects and return values
37
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**.
38
**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
39
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**
40
Ruby methods: Has a "\_\_\_\_\_\_" statement
Has a "**return**" statement
41
Ruby methods: Take \_\_\_\_\_\_\_\_
Take **arguments**
42
Ruby methods: Between "\_\_\_" "\_\_\_" pairs
•Between "**def**" "**end**" pairs
43
**Ruby methods:** But also returns last _________ \_\_\_\_\_\_\_\_
But also returns last **expression evaluated**
44
**Creating and Extending Objects in Ruby**
obj = Object.new def obj.talk puts "I am an object" end obj.talk
45
**Objects have Identifiers**
s1 = "Hello" s2 = "Hello" p s1.object\_id p s2.object\_id
46
**What does this output?** s1 = "Hello" s2 = "Hello" p s1.object\_id p s2.object\_id
$ ruby ref.rb 70235101628760 70235101628740
47
**Passing Parameters**
obj = Object.new def obj.c2f(c) c \* 9.0 / 5 + 32 end p obj.c2f(100) p obj.c2f 100
48
**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 212. 0 212. 0
49
**Optional Arguments**
obj = Object.new def obj.multi(\*x) p x end obj. multi() obj. multi(1) obj. multi(1,2,3)
50
**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]
51
**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)
52
**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]
53
**Default Arguments**
obj = Object.new def obj.default(a,b=3) p "#{a}, #{b}" end obj. default(1) obj. default(1,4)
54
**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"
55
**List Ruby variables**
* Locals: start with lowercase or underscore * Instance: start with ‘@’ * Class: start with ‘@@’ * Globals: start with ‘$’ * Constants begin with uppercase
56
Local Variables
•Locals: start with lowercase or underscore
57
Instance Variables
•Instance: start with ‘@’
58
Class Variables
•Class: start with ‘@@’
59
Global Variables
•Globals: start with ‘$’
60
Constant Variables
•Constants begin with uppercase
61
**All Variables are References**
•All Variables are References –No base types as in other language (e.g. integer, float, string, etc.) •Refer to Objects
62
**All Variables are References** ## Footnote 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"
63
**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"
64
Freeze Method ## Footnote 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 `
'
65
**Ruby Classes**
* Class names are constants * Define methods/messages * Can reopen * Can override
66
**Override** ## Footnote class A def m "one" end def m "two" end end p A.new.m **What will this happen?**
$ ruby ref.rb "two"
67
**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 `
': undefined method `n' for #<0x007f89f411cfd0> (NoMethodError)0x007f89f411cfd0>
68
**Reopen** **What will this code output?**
$ ruby ref.rb "two" "three"
69
**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
70
**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
71
**Writing and Both methods**
•attr\_writer and attr\_accessor
72
**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”
73
**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
74
**Superclasses**
\>\> Programmer.superclass =\> Human \>\> Programmer.superclass.superclass =\> Object
75
**Class Variables and Methods**
* Variables or methods where only one exists per class * Every object of the class shares them
76
**Class Variable** ## Footnote 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
77
**“Constant”** ## Footnote 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
78
**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.
79
**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.
80
**Class Methods** **What will this output?**
$ ruby ref.rb main C C #\<0x007ffb3c84c940\>0x007ffb3c84c940\>
81
Scope ## Footnote 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
82
**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
83
**Private and Protected** **What will this output?**
$ ruby ref.rb "yep" "derived" ref.rb:25:in `
': private method `nope' called for #<0x007fb869994408> (NoMethodError)0x007fb869994408>
84
**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
85
**Allocation in Conditionals** if false x = 1 end p x p y **What will this output?**
$ ruby ref.rb nil ref.rb:5:in `
': undefined local variable or method `y' for main:Object (NameError)
86
**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"
87
**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
88
**Case** ## Footnote 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"
89
**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) person3 = Person.new("Alice", 40) ----------------------------------------------------------- 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
90
Else in Case ## Footnote 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
91
**Loops** ## Footnote n = 0 loop do n = n + 1 puts n break if n \> 5 end **What will this output?**
1 2 3 4 5 6
92
**While** ## Footnote n = 0 while n \< 5 n = n + 1 puts n end **What will this output?**
1 2 3 4 5
93
**Begin/While** n = 0 begin n = n + 1 puts n end while n \< 5 **What will this output?**
1 2 3 4 5
94
**Until** n = 0 until n \> 5 n = n + 1 puts n end **What will this output?**
1 2 3 4 5 6
95
**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
96
**3 loop features**
* Loops really just repeatedly execute code blocks * I.e.: they are iterators * Iterators repeatedly “yield” to code blocks
97
**Code Blocks**
* Defined inside "{}"or "do" * Passed as parameters * Called via "yield"
98
**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
99
**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
100
**Exceptions** ## Footnote 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 `
'
101
**Ruby Symbols**
* Begin with ‘:’ * More similar to integers than strings * Are immutable * Are unique * Used to refer to methods * Often used in hashes
102
**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
103
Numbers
•Numeric –Float –Integer * Fixnum * Bignum
104
**Hashes**
* Key/value pairs * Use "{}" as literal
105
**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
106
**Older Symbol**
hash = { :red =\> "ruby", :white =\> "diamond", :green =\> "emerald" }
107
**Newer Symbol**
hash = { red: "ruby", white: "diamond", green: "emerald" }
108
**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]
109
**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"]
110
**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"]
111
**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]
112
**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]
113
**Each Takes an Array and a Block** ## Footnote [1,2,3].each {|i| puts "Received #{i}"}
$ ruby ref.rb Received 1 Received 2 Received 3
114
**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"]
115
**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
116
**Closure** ## Footnote 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
117
118
**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
119
Ruby features: Interactive \_\_\_\_\_\_\_\_(a REPL (\_\_\_\_\_\_\_\_/\_\_\_\_\_\_\_\_/\_\_\_\_\_\_\_\_)) -- IRB
•Interactive **Ruby Shel**l (a REPL (**Read/Execute/Print Loop**)) -- IRB
120
121