Explain each of the following operators and how and when they should be used: ==, ===, eql?, equal?.

==  Checks if the value of two operands are equal (often overridden to provide a class-specific definition of equality).

===  Specifically used to test equality within the when clause of a case statement (also often overridden to provide meaningful class-specific semantics in case statements). === is the pattern matching operator!

 

=== matches regular expressions
=== checks range membership
=== checks being instance of a class
=== calls lambda expressions
=== sometimes checks equality, but mostly it does not


Some examples

case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end

 

eql?  Checks if the value and type of two operands are the same (as opposed to the == operator which compares values but ignores types). For example, 1 == 1.0 evaluates to true, whereas 1.eql?(1.0) evaluates to false.

equal?  Compares the identity of two objects; i.e., returns true iff both operands have the same object id (i.e., if they both refer to the same object). Note that this will return false when comparing two identical copies of the same object.

(Thanks to Ruby Gotchas for this question.)

Given:x = "hello"Explain the difference between:x += " world"andx.concat " world"

The += operator re-initializes the variable with a new value, so a += b is equivalent to a = a + b.

Therefore, while it may seem that += is mutating the value, it’s actually creating a new object and pointing the the old variable to that new object.

This is perhaps easier to understand if written as follows:

  foo = "foo"
  foo2 = foo
  foo.concat "bar"

  puts foo
  => "foobar"
  puts foo2
  => "foobar"

  foo += "baz"
  puts foo
  => "foobarbaz"
  puts foo2
  => "foobar"

(Examining the object_id of foo and foo2 will also demonstrate that new objects are being created.)

The difference has implications for performance and also has different mutation behavior than one might expect.

In Ruby code, you quite often see the trick of using an expression like array.map(&:method_name)as a shorthand form ofarray.map { |element| element.method_name }How exactly does it work?

When a parameter is passed with & in front of it (indicating that is it to be used as a block), Ruby will call to_proc on it in an attempt to make it usable as a block. Symbol #to_proc quite handily returns a Proc that will invoke the method of the corresponding name on whatever is passed to it, thus enabling our little shorthand trick to work.

Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.(Hint: use inject)

There are multiple ways to do this, but one possible answer is:

(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) }

As you go up the sequence fib, you sum, or inject(:+), the last two elements in the array and add the result to the end of fib.

What does the “$” character mean in Ruby?

$ identifies a global variable, as opposed to a local variable, @instance variable, or @@class variable. This is one of the pre-defined Ruby global variables. All globals are prefixed with $, and in this case $$ represents the current process ID. This was inherited from Perl.

What is the difference between clone and dup methods in Ruby?

clone copies the singleton class, while dup does not.

o = Object.new
def o.foo
  42
end

o.dup.foo   # raises NoMethodError
o.clone.foo # returns 42

Second, clone preserves the frozen state, while dup does not.

class Foo
  attr_accessor :bar
end
o = Foo.new
o.freeze

o.dup.bar = 10   # succeeds
o.clone.bar = 10 # raises RuntimeError


 

Difference between map, collect, select, reject, each, inject, reduce, find and detect methods in ruby?

  • map (collect)

    map takes the enumerable object and a block, evaluates the block for each element and then return a new array with the calculated values. The original array is not modified. The collect method is same as map.
    a = [1,2,3,4,5]
    
    a.map{ |e| e * 2 }
    
    # =>  [2,4,6,8,10]

    If you are try to use map to select any specific values like where e %2 == 0 then it will evaluate each element and will output only the result which will be either true or false

    [1,2,3,4,5].map{ |e| e %2 == 0 }
    
    # => [false, true, false, true, false]
  • collect

    Alias for map
  • select

    select evaluates the block with each element for which the block returns true.

    [1,2,3,4,5,6,7,8,9,10].select{ |e| e > 5 }
    
    # => [6 ,7, 8, 9, 10]


    select would also return an element for which the statement is true. 

    [1,2,3,4,5,6,7,8,9,10].select{ |e| e * 3 }
    
    # => [1,2,3,4,5,6,7,8,9,10]
  • reject

    The opposite of select. reject method runs an expression for each array element and returns an array of elements for which the expression is false.

    [1,2,3,4,5,6,7,8,9,10].reject{|e| e % 2 == 0 }
    # returns [1, 3, 5, 7, 9]

     

  • each

    Executes an action using as parameter each element of the array. Returns the unmodified array.
    [1,2,3,4,5,6,7,8,9,10].each{|e| print e.to_s+"!" }
    # prints "1!2!3!4!5!6!7!8!9!10!"
    # returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

     

  • inject (reduce)

    Takes an accumulator (sum) and changes it as many times as there are elements in the array. Returns the final value of the accumulator. 

    [6,7,8,9,10].inject(15){ |sum, e| sum += e }
    # => 55
    
    


    If you do not explicitly specify an initial value for accumlator, the inject method uses the first element of collection as the initial value of the accumulator.

    [1,2,3,4,5].inject{ |sum, e| sum += e }
    # => 15

     

  • reduce

    Alias for inject

  • find

    Take an expression and returns the first element for which the expression is true:

    [1,2,3,4,5,6,7,8,9,10].find{|e| e % 2 == 0}
    # returns 2

     

  • Detect

    Alias for find

What is an object?

An instance of a class.
To some, it''s also the root class in ruby (Object).
Classes themselves descend from the Object root class. (Kudos to Ezra)

gem vs engine vs plugin

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Log In or Sign Up in a few seconds to view this answer.

What is a class?

A text-book answer: classes are a blue-print for constructing computer models for real or virtual objects... boring.
In reality: classes hold data, have methods that interact with that data, and are used to instantiate objects.
Like this.

class WhatAreClasses
  def initialize
    @data = "I''m instance data of this object. Hello."
  end

  def method
    puts @data.gsub("instance", "altered")
  end
end

object = WhatAreClasses.new
object.method
 #=> I''m altered data of this object. Hello.