a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return
[1,3,2] <=> [2,2,2]
- Ruby will start comparing each element of
both array from left hand side.
- 1 of left array is smaller than 2 of right
- Hence left array is smaller than right array.
Output will be -1.
case subsumption operator or case
- "If I have a drawer labelled a would it
make sense to put b in that drawer?"
- The main usage for the === operator is in
a === b
# Here b === a check is made in when
# not b == a
Diff between a == b and a === b
- (a == b) and (b == a) is always the same
- (a === b) and (b === a) is not always the
Integer === 2 #true
2 === Integer #false
We just used double splat to capture all
def join_array(arr, elements: , by_char: ‘,’)
a = [20, 30, 10, 40]
# optional if there is default set in parameters, in this case it is by_char
p join_array(a, elements: 3)
p join_array(a, elements: 2, by_char: ‘-’)
# order not important
p join_array(a, by_char: ‘-’, elements: 3)
Damn! lambda is not rhyming! :/
blocks, procs and lambdas
puts “Yo. Get lots of free stuff.”
alias_method :money_time, :free_scheme
Politics.new.free_scheme # what you see :P
Politics.new.money_time # what they see :P
(Do not try this at your home/code)
not found is not an option for you
Use it only when method
refine String do
self.reverse == self
#=> NoMethodError: undefined method `palindrome?' for "Ruby":String
#Not available outside the namespace
And how did you define on an object?
But only classes has methods
a singleton class(invisible to you) for the object
You are right. Ruby makes
just to hold object specific methods
have singleton classes not only objects
You know what, even classes
singleton class for the class just to hold
So, ruby makes a
class specific methods ?
Foo and Foo.new are objects
Wait, I remember you saying
the class to hold the class specific methods
So, actually ruby is making a singleton class for
just like it does for object because class is
invisible to the programmer.
AH! Yes! And The singleton class is typically
But you sorta see in one syntax, which is
class << self
class << self is like class Singleton(self)
- You want to add a method just to a specific
object. (note: even class is an object)
- But you can’t write method to a object.
- So, you write method to object’s singleton
class like this.
matz = Human.new
class << matz
puts “Writing the epic: Ruby”