Saturday, 7 December 2013

Ruby

Use ClassName.instance_eval to define a class method (one associated with the class object but not visible to instances).
Use ClassName.class_eval to define an instance method (one that applies to all of the instances of ClassName).

class Person end Person.class_eval do def say_hello "Hello!" end end jimmy = Person.new jimmy.say_hello # "Hello!"

class Person end Person.instance_eval do def human? true end end Person.human? # true

=====
=>Why ruby doesn't suppoert method overloading?
A.Method overloading can be achieved by declaring two methods with the same name and different signatures. These different signatures can be either,

Arguments with different data types, eg: method(int a, int b) vs method(String a, String b)
Variable number of arguments, eg: method(a) vs method(a, b)
We cannot achieve method overloading using the first way because there is no data type declaration in ruby(dynamic typed language). So the only way to define the above method is def(a,b)

With the second option, it might look like we can achieve method overloading, but we can't. Let say I have two methods with different number of arguments,

def method(a); end;
def method(a, b = true); end; # second argument has a default value

method(10)
# Now the method call can match the first one as well as the second one,
# so here is the problem.
So ruby needs to maintain one method in the method look up chain with a unique name.
=>can be achived using
I presume you are looking for the ability to do this:

def my_method(arg1)
..
end

def my_method(arg1, arg2)
..
end
Ruby supports this in a different way:

def my_method(*args)
  if args.length == 1
    #method 1
  else
    #method 2
  end
end
        OR
def f(*args)
  case args.size
  when
     ...
  when 2
    ...
  when 3
    ...
  end
end      


===================================
=>Ruby polimorphism?
A.An object takes on multiple shapes or forms.
class Animal
  def sleep
    puts "#{self.class} is sleeping"
  end
end

class Dog < Animal
  def make_noise
    "Woof!"
  end
end

class Cat < Animal
  def make_noise
    "Meow!"
  end
end

[Dog, Cat].each do |obj|
  animal = obj.new
  animal.make_noise
  puts animal.sleep
end
=================================
=>Ruby Encapsulation?
A. Encapsulation is the ability for an object to have certain methods and attributes available for use publicly (from any section of code), but for others to be visible only within the class itself or by other objects of the same class. "

=================================
=>Metaprogramming in ruby?
A. writing code that writes code during runtime to make your life easier.
=================================

=>Why java is not pure OOP?
A. OOP language always deals with only objects that is, every thing should be object whereas in java we use primitive data type(int, float ) that are not objects, so java in not pure OOP but more OOP supported than C language. Hence concept of wrapper classed (Integer etc)has been introduced in Java to resolve these non-object data type.


Yes you are right...Java is not pure Object oriented because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects...

Above concept this called autoboxing.

Autoboxing: Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes


============================
The g stands for global, as in replace globally (all):

In irb:

>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"
=============================
=>Array vs Hash?
=It's more efficient to access array elements, but hashes provide more flexibility.
=Many times a hash can be more convenient than an array.
=no order in hash in 1.8
=The use of a compound key (or hash of hashes) can be used to simulate multidimensional arrays.
2D arrays are no sweat

array = [[1,2],[3,4],[5,6]]
 => [[1, 2], [3, 4], [5, 6]]
array[0][0]
 => 1
array.flatten
 => [1, 2, 3, 4, 5, 6]
array.transpose
 => [[1, 3, 5], [2, 4, 6]]
For loading 2D arrays try something like:

rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }
===============================
=>set?
Set

Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.
require 'set'
s1 = Set.new [1, 2]                   # -> #<Set: {1, 2}>
s2 = [1, 2].to_set                    # -> #<Set: {1, 2}>
s1 == s2                              # -> true
s1.add("foo")                         # -> #<Set: {1, 2, "foo"}>
s1.merge([2, 6])                      # -> #<Set: {6, 1, 2, "foo"}>
s1.subset? s2                         # -> false
s2.subset? s1                         # -> true
===============================


=> .create vs .build?
          1=(2.X)>Build is different from New. But the difference is not that it sets the association link (New does that too for the new instance). The difference is that Build populates the caller with the new instance, but New doesn't. So for example: Wall.posts.new gives you a new post associated with your Wall, but Wall.posts is still empty after this call. Wall.posts.build gives you a new post associated with your Wall, and your Wall.posts now has one post in it.

          =>If you're creating an object through an association, build should be preferred over new as build keeps your in-memory object, some_firm (in this case) in a consistent state even before any objects have been saved to the database.

          [OR]
        2=(3.X)>You are correct, the build and new functions have the same effect of setting the foreign key, when they are called through an association. I believe the reason the documentation is written like this is to clarify that a new Client object is being instantiated, as opposed to a new active record relationship. This is the same effect that calling .new on a class would have in Ruby. That is to say that the documentation is clarifying that calling build on an association is the same is creating a new object (calling .new) and passing the foreign keys to that object. These commands are all equivalent:

          Firm.first.clients.build
          Firm.first.clients.new
          Client.new(:firm_id => Firm.first.id)
          I believe the reason .build exists is that Firm.first.clients.new might be interpreted to mean that you are creating a new has_many relationship object, rather than an actual client, so calling .build is a way of clarifying this.
=============
    ruby overriding?
          Method overriding, in object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.


          class A
            def a
              puts 'In class A'
            end
          end

          class B < A
            def a
              puts 'In class B'
            end
          end

          b = B.new
          b.a

          A)In class B

============
          palindrome?

          =>
          pal = "Never a foot too far, even."
          (* optionsal class String )
          def palindrome?
            letters = self.downcase.scan(/\w/)
            letters == letters.reverse
          end
          (* end )
          pal.palindrome? #=> true



============

          Prime.each(100) do |prime|
            p prime  #=> 2, 3, 5, 7, 11, ...., 97
          end


============
          def isPrime(number)
            if number == 0 or number == 1
              return false
            end
            i = 2
            limit = number / i
            while i < limit
              if number % i == 0
                return false
              end
              i += 1
              limit = number / i
            end
            return true
          end
          isPrime(19) #=> true
          =====


          def is_prime(n)
            ("1" * n) !~ /^1?$|^(11+?)\1+$/
          end

          =====

          class Prime_number
            def get_value
              print "enter number :"
              i = gets.chomp.to_i
              prime = true
              for counter in 2..(Math.sqrt(i)) do
                if i % counter == 0 then
                  prime = false
                end
              end
              if prime then
                puts "\n Given number is Prime"
              else
                puts "\n Given number is composite"
              end
            end
          end
          a = Prime_number.new
          a.get_value


          ====
          require 'mathn'

          def prime_numbers_from start, n
            primes = []
            Prime.each(n) do |prime|
              primes << prime if prime > start
            end
            primes
          end

          prime_numbers_from(10, 30)
          ============

          # To print sum of N natural numbers
          print " Enter the number: "
          number=gets.chomp.to_i
          sum = 0
          for iterator in 1..number do
            sum = sum + iterator
          end
          puts
          puts " Sum of N numbers is " + sum.to_s
          # Main of the program ends here

          ============
          size vs length vs count in ruby?

          =>if you already load all entries, say User.all, then you should use length to avoid another db query

            if you haven't anything loaded, use count to make a count query on your db

              if you don't want to bother with these considerations,
                Note:For example if you create a new record without going through the relation, i.e. Comment.create(post_id: post.id), your post.comments.size will not be up to date, while post.comments.count will. So just be careful.
                OR

                =>In Ruby, #length and #size are synonyms and both do the same thing: they tell you how many elements are in an array or hash. Technically #length is the method and #size is an alias to it.

                In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.

                post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g. :conditions => {:author_name => "josh"}). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.
                post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments were created through another way (e.g. Comment.create(...) instead of post.comments.create(...)).
                  post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.

============

                  ruby inject vs reduce?
                  http://blog.nathanhumbert.com/2008/09/using-injectreduce-to-create-hashes-tml

                  ============

                  ruby datatypes?

                  :binary
                  :boolean
                  :date
                  :datetime
                  :decimal
                  :float
                  :integer
                  :primary_key
                  :references
                  :string
                  :text
                  :time
                  :timestamp

                  ============
                  datatypes diff b/w mysql vs postgres vs sqlite vs mongodb vs oracle?




                  split vs join vs scan?

                  names = "Alice,Bob,Eve"
                  names_a = names.split(/,/)   A# ["Alice", "Bob", "Eve"]


                  names_a.push("Carol", "Dave")
                  names = names_a.join(',')  A#  "Alice,Bob,Eve,Carol,Dave"

                  puts names
                  ===========
          # Split on everything between and including two t's
                  "a|delimited|string".split(/t.+t/)
                  # Prints: ["a|delimi", "ring"]

                  # Search for everything between and including two t's
                  "a|delimited|string".scan(/t.+t/)
                  # Prints: ["ted|st"]

============
                  ruby step method?
                  it skips n values(opp to each)
                  $(1..22).step(2){|x| puts x}
                  A)
                  1
                  3
                  5
                  7
                  9
                  11
                  13
                  15
                  17
                  19
                  21

                  ============
                  save vs save! ?
                  Anything with an exclamation with raise an error if it is not
                  successful, without an exclamation it will just return false

                  ============
                  singleton?
============
                  comments ?

                  coffescript:
                  ###
                  asjfdklj
                  sakdfja
                  ###

                  # A comment
                  ========
                  javascript:

                  /*
                  The code below will write
                  to a heading and to a paragraph,
                  and will represent the start of
                  my homepage:
                  */

                  // Write to a heading:
                                ========
                  rails view:

                  <% comment do %>
                    .. Some HTML
                    .. Some ruby scriptlets
                    <% end %>

                    def comment(&block)
                      #SWALLOW THE BLOCK
                    end

                    <%
=begin
This is a multiline comment you can add to your .html.erb files.
Whatever you place in these comments won't show up in your rendered HTML.
You now have a place to put comments in your views. This will help
you better understand what you did later on.

========
HAML
%p foo
-# This is a comment
%p bar
============
Ruby:
http://stackoverflow.com/questions/21574/what-is-the-difference-between-ruby-1-8-and-ruby-1-9/1426144#1426144

ruby 1.9 features:
Performance
Threads/Fibers
Encoding/Unicode
gems is (mostly) built-in now
if statements do not introduce scope in Ruby.
======================


===========
=>include is for adding methods to an instance of a class and extend is for adding class methods. Let’s take a look at a small example.
http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/

module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>
===============================
call methods using
   ., send(:name),method(:name).call
===========================================
methods in application.html.erb like=> title

===========================================
http://www.allfreshersworld.com/tag/ruby-on-rails-interview-questions/

===========================================

singleton methods

 instance would have special behavior that it can have direct method
*A method given only to a single object is called a singleton method.
ruby> class SingletonTest
    |   def size
    |     25
    |   end
    | end
   nil
ruby> test1 = SingletonTest.new
   #<SingletonTest:0xbc468>
ruby> test2 = SingletonTest.new
   #<SingletonTest:0xbae20>
ruby> def test2.size
    |    10
    | end
   nil
ruby> test1.size
   25
ruby> test2.size
   10
===========================================
ruby 1.9.2:
  ===========
  http://nuclearsquid.com/writings/ruby-1-9-what-s-new-what-s-changed/
>> ?c
=> "c"

>> "ruby"[1]
=> "u"

>> i = 0
=> 0
>> [1,2,3].each{|i|}
=> [1, 2, 3]
>> i
=> 0

NEW:
>> {:a => "b"}
=> {:a=>"b"}
>> {a: "b"}
=> {:a=>"b"}

>> (1..10).to_a.inject(:+)
=> 55


>> enum = (1..4).to_enum
=> #<Enumerator:0x1344a8>
>> enum.each{|i| puts i}
1
2
3
4
=> 1..4
>> enum.next
=> 1
>> enum.next
=> 2


=================
ruby access specifiers?
Public methods enforce no access control — they can be called in any scope.
Protected methods are only accessible to other objects of the same class.
Private methods are only accessible within the context of the current object.
==================================
What does self mean?
self always refers to the current object. But this question is more difficult than it seems because Classes are also objects in ruby. (Kudos to Stephen)
class WhatIsSelf
  def test
    puts "At the instance level, self is #{self}"
  end
  def self.test
    puts "At the class level, self is #{self}"
  end
end
WhatIsSelf.test
 #=> At the class level, self is WhatIsSelf
WhatIsSelf.new.test
 #=> At the instance level, self is #<WhatIsSelf:0x28190>
This short snippet indicates two things:

at the class level, self is the class, in this case WhatIsSelf.
at the instance level, self is the instance in context, in this case the instance of WhatIsSelf at memory location 0×28190.
==================================
Understanding blocks, Procs and methods

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Understanding_blocks.2C_Procs_and_methods
==================================

Lambda?
Proc?
proc not bother about parameters, where as lambda bother..means no.of parameters are mandatory in lambda

==================================
RACK:
=====
CGI was first widely used method of running Ruby scripts on server-side. You could run it like shell, perl or python scripts inside Apache using special module. Apache and FastCGI was preffered method of deploying Rails applications, until it was replaced by solutions using HTTP proxy and a “cluster” of dedicated Ruby servers (e.g. Mongrel). When Phusion Passenger (mod_rails) arrived and started supporting Rack – we had clear winner: Rack dominated Ruby web development world.(http://amberbit.com/blog/introduction-to-rack-middleware)


Rake:
=====
Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks.

Yield in Ruby:
=============
Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.

#!/usr/bin/ruby

def test
   puts "You are in the method"
   yield
   puts "You are again back to the method"
   yield
end
test {puts "You are in the block"}
This will produce following result:

You are in the method
You are in the block
You are again back to the method
You are in the block
You also can pass parameters with the yield statement. Here is an example:

#!/usr/bin/ruby

def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}
This will produce following result:

You are in the block 5
You are in the method test
You are in the block 100

=======================================
Ruby's yield statement gives control to a user specified block from the method's body.
class NumericSequences
   def fibo(limit)
     i = 1
     yield 1
     yield 1
     a = 1
     b = 1
     while (i < limit)
         t = a
         a = a + b
         b = t
         yield a
         i = i+1
     end
  end
  ...
end



The fibo method can be used by specifying a block that will be executed each time the control reaches a yield statement. For example:
capistrano  deployment:    http://guides.beanstalkapp.com/deployments/deploy-with-capistrano.html


irb(main):001:0> g = NumericSequences::new
=> #<NumericSequences:0xb7cd703c>
irb(main):002:0> g.fibo(10) {|x| print "Fibonacci number: #{x}\n"}
Fibonacci number: 1
Fibonacci number: 1
Fibonacci number: 2
Fibonacci number: 3
Fibonacci number: 5
Fibonacci number: 8
Fibonacci number: 13
Fibonacci number: 21
Fibonacci number: 34
Fibonacci number: 55
Fibonacci number: 89
=======================
include : mixes in specified module methods as instance methods in the target class
extend : mixes in specified module methods as class methods in the target class

lamda vs proc: http://techspry.com/ruby_and_rails/proc-and-lambda-in-ruby/
=======================

=>tap mehtod?

Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

(1..10)                .tap {|x| puts "original: #{x.inspect}"}
  .to_a                .tap {|x| puts "array: #{x.inspect}"}
  .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
  .map { |x| x*x }     .tap {|x| puts "squares: #{x.inspect}"}

===================
=> ruby MX record?

A. A mail exchanger record (MX record). The set of MX records of a domain name specifies how email should be routed with the Simple Mail Transfer Protocol (SMTP)
==================
=>Duck Typing in ruby?
A.In Ruby, we rely less on the type (or class) of an object and more on its capabilities. Hence, Duck Typing means an object type is defined by what it can do, not by what it is. Duck Typing refers to the tendency of Ruby to be less concerned with the class of an object and more concerned with what methods can be called on it and what operations can be performed on it. In Ruby, we would use respond_to? or might simply pass an object to a method and know that an exception will be raised if it is used inappropriately.
============

=>is ruby is dynamic type language?
A.yes,Dynamic typing means you don't need to define the type of a variable, the language interpreter will try to guess the type of that variable (number, boolean, string etc).
============

=>closure?
FFI closure wrapper, for handling callbacks.

closure = Class.new(Fiddle::Closure) {
  def call
    10
  end
}.new(Fiddle::TYPE_INT, [])
   #=> #<#<Class:0x0000000150d308>:0x0000000150d240>
func = Fiddle::Function.new(closure, [], Fiddle::TYPE_INT)
   #=> #<Fiddle::Function:0x00000001516e58>
func.call
   #=> 10
============
=>struct?
A.A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.
Customer = Struct.new(:name, :address) do
  def greeting
    "Hello #{name}!"
  end
end
Customer.new("Dave", "123 Main").greeting  # => "Hello Dave!"
============
=>Design patterns

1.Observer:-As an example, imagine a instant deal service. This service allows people to subscribe to receive instant deals via email or text messages. Our design needs to be flexible enough to support any other future kind of message delivery.

2. Strategy:-As an example let’s think of fighters, more specifically, boxers, mixed martial artist and Mortal Kombat warriors. We know that all fighters have a special attack to finish their opponent, but that special attack is different for each fighter. This finishing attack can be a straight right punch to the face of the opponent or a left hook to the body. Whatever it is, it is different for each fighter.
The Strategy Pattern suggest that we define a family of behaviors in order to separate these parts that change from each object. In this case our object Fighter has a different finishing move, so we need to create a separate family of Fighting behaviors.

==============
=>class_attribute
A.Declare a class-level attribute whose value is inheritable by subclasses. Subclasses can change their own value and it will not impact parent class.

class Base
  class_attribute :setting
end

class Subclass < Base
end

Base.setting = true
Subclass.setting            # => true
Subclass.setting = false
Subclass.setting            # => false
Base.setting                # => true

=================
=>Change keys of a hash?

ages = { "Bruce" => 32, "Clark" => 28 }
mappings = {"Bruce" => "Bruce Wayne", "Clark" => "Clark Kent"}

Hash[ages.map {|k, v| [mappings[k], v] }]

======================
=>predicate method?

t returns a "truthy" value that is either "truthy-true" or "truthy-false".

In Ruby, there are only two things that are truthy-false:

false (the singleton object)
nil (the singleton object)
Anything else is considered truthy-true. Tons of Ruby code leverages this fact for predicates. Checks for predicates, as such, should be:

if list.empty?
not:

if list.empty? == true

=======================
=>Ruby aalias_attribute(new_name, old_name) public?

Allows you to make aliases for attributes, which includes getter, setter, and query methods.

Example:

class Content < ActiveRecord::Base
  # has a title attribute
end

class Email < Content
  alias_attribute :subject, :title
end

e = Email.find(1)
e.title    # => "Superstars"
e.subject  # => "Superstars"
e.subject? # => true
e.subject = "Megastars"
e.title    # => "Megastars"
=======================
=>alias_method(p1, p2) private?
Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

module Mod
  alias_method :orig_exit, :exit
  def exit(code=0)
    puts "Exiting with code #{code}"
    orig_exit(code)
  end
end
include Mod
exit(99)

====================
=>reverse_merge(other_hash) public?

Merges the caller into other_hash. For example,

options = options.reverse_merge(:size => 25, :velocity => 10)
is equivalent to

options = {:size => 25, :velocity => 10}.merge(options)
This is particularly useful for initializing an options hash with default values.


====================
=>Singleton class
A. A Singleton class is needed when you need to have only one instance of the class. A very good example of the Singleton class in a widely accepted framework is the Rails Logger class.


=============






=>what is splat operator in ruby?
A.That is the double splat operator which is available since Ruby 2.0.

  For this code:
def foo(a, *b, **c)
  [a, b, c]
end
Here's a demo:
> foo 10
=> [10, [], {}]
> foo 10, 20, 30
=> [10, [20, 30], {}]
> foo 10, 20, 30, d: 40, e: 50
=> [10, [20, 30], {:d=>40, :e=>50}]
> foo 10, d: 40, e: 50
=> [10, [], {:d=>40, :e=>50}]

=========
=>What is compact in ruby ?
[ "a", nil, "b", nil, "c", nil ].compact
#=> [ "a", "b", "c" ]


============
diff b/w self.method,classname.method?
=>http://stackoverflow.com/questions/863782/trying-to-understand-use-of-self-method-name-vs-classname-method-name-in-ruby

constants in ruby?
=>http://ruby.about.com/od/advancedruby/a/Constants-In-Ruby.htm

DIFFERECE B/W Java & Ruby
========================
https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/

Similarities

Memory is managed for you via a garbage collector.
Objects are strongly typed.
There are public, private, and protected methods.
There are embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc.

Differences


You don’t need to compile your code. You just run it directly.
There are several different popular third-party GUI toolkits. Ruby users can try WxRuby, FXRuby, Ruby-GNOME2, Qt, or the bundled-in Ruby Tk for example.
You use the end keyword after defining things like classes, instead of having to put braces around blocks of code.
You have require instead of import.
All member variables are private. From the outside, you access everything via methods.
Parentheses in method calls are usually optional and often omitted.
Everything is an object, including numbers like 2 and 3.14159.
There’s no static type checking.
Variable names are just labels. They don’t have a type associated with them.
There are no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
There’s no casting. Just call the methods. Your unit tests should tell you before you even run the code if you’re going to see an exception.
It’s foo = Foo.new("hi") instead of Foo foo = new Foo("hi").
The constructor is always named “initialize” instead of the name of the class.
You have “mixins” instead of interfaces.
YAML tends to be favored over XML.
It’s nil instead of null.
== and equals() are handled differently in Ruby. Use == when you want to test equivalence in Ruby (equals() is Java). Use equal?() when you want to know if two objects are the same (== in Java).

====================


Describe the environment variables present in Ruby.
RUBYOPT, RUBYLIB, RUBYPATH, RUBYSHELL,RUBYLIB_PREFIX...................

Interpolation is a very important process in Ruby, comment.
Interpolation is the process of inserting a string into a literal..............


What is the use of super in Ruby Rails?
Ruby uses the super keyword to call the superclass implementation of the current method.............

What are the object-oriented programming features supported by ruby?
Classes,Objects,Inheritance,Singleton methods,polymorphism(accomplished by over riding and  overloading) are some oo concepts  supported by ruby.

What are the looping structures available in ruby?
for..in

untill..end

while..end

do..end

puts is from which package
=>kernal module and IO class

================
method overloading
http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/
http://www.rootr.net/rubyfaq-8.html


Module vs Class?
=>When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance".


singleton?
=>ruby: http://www.rubyist.net/~slagell/ruby/singletonmethods.html
In Ruby, methods can be defined that are associated with specific objects only. Such methods are called singleton methods.

ruby yield?
=>The yield statement executes a block that is passed to the method.
Executes the block passed to the method. The expression passed to yield is assigned to the block's arguments.
Parallel assignment is performed when multiple expressions are passed. The output of the block, in other words
the result of the last expression in the block, is returned.

======================


nil vs false?
 nil cannot be a value, where as a false can be a value
- A method returns true or false in case of a predicate, other wise nil is returned.
- false is a boolean data type, where as nil is not.
- nil is an object for NilClass, where as false is an object of for FalseClass



=================

Diff include,extend,load,require?
=>http://www.rorexperts.com/the-difference-between-require-load-include-and-extend-t1564.html
=> You use load() to execute code, and you use require() to import libraries.
=>The require method runs another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

Diff ruby 1.8.7, 1.9.2 ?
=>


ruby string vs symbol?
=>The main difference is that multiple symbols representing a single value are unique whereas this is not true with strings. Although symbols are not cleaned up by the garbage collector and stick around until the end of the runtime instance. So if you declare a lot of symbols you might be wasting a lot of memory. You would want to use a symbol when you may have need to use a string several times as this far easier and more productive.


=================

alternative ruby frameworks ?
=>Merb, Camping, Ramaze, Halcyon, Vintage, Halcyon, Wuby, Nitro/Og, Sinatra, Ruby WAF, webby


=============


recompile the ruby s/w code after install dependencies:
cd ruby_install(folder)
cd ruby(version)
cd ext/openssl
ruby extconf.rb
make
sudo make install



delete vs destroy
===========================================
call methods using
   ., send(:name),method(:name).call
===========================================
methods in application.html.erb like=> title

===========================================
http://www.allfreshersworld.com/tag/ruby-on-rails-interview-questions/

===========================================

singleton methods

 instance would have special behavior that it can have direct method
*A method given only to a single object is called a singleton method.
ruby> class SingletonTest
    |   def size
    |     25
    |   end
    | end
   nil
ruby> test1 = SingletonTest.new
   #<SingletonTest:0xbc468>
ruby> test2 = SingletonTest.new
   #<SingletonTest:0xbae20>
ruby> def test2.size
    |    10
    | end
   nil
ruby> test1.size
   25
ruby> test2.size
   10
===========================================

search a word in a directory

$ grep -Hrn 'search term' path/to/


==================================

DIFF B/W  RUBY 1.9 vs 2.0
http://globaldev.co.uk/2013/03/ruby-2-0-0-in-detail/

Added keyword arguments.

Added %i and %I for symbol list creation (similar to %w and %W).

Default source encoding is changed to UTF-8. (was US-ASCII)

No warning for unused variables starting with ‘_’


additions:

=>'prepend' instead of 'include' with model
=> we can convert everything into to_h (-:hash ex: nil.to_h => {}
=>array#bsearch
=>Unbound methods from a module can be bound to any object
=>const_get
=>Enumerable#lazy,size
     (1..10).size  => error OR 10
=>gem install --file Gemfile,export RUBYGEMS_GEMDEPS=-  <-: # start your app >
=>TracePoint
=>#inspect no longer calls #to_s
===


DIFF B/W  RUBY 1.9 vs 2.0
http://slideshow.rubyforge.org/ruby19.html#1

=>char ?a => 97 OR "a"
=>string "rama"[1] ->97 OR "a",
=>{1,2} => {1=>2} OR error
=>[1,2,3].to_s => "123" OR "[1, 2, 3]"
=> when with : => allowed OR error
=>Has index(2) => allowed OR deprecated
=>5.to_sym =>nil OR error
=>Hash => sort OR unsort
=>Class of Class C => C OR String
=>{a:1} => error OR {:a=>1}

====================
ruby access specifiers?
Public methods enforce no access control — they can be called in any scope.
Protected methods are only accessible to other objects of the same class.
Private methods are only accessible within the context of the current object.
==================================
What does self mean?
self always refers to the current object. But this question is more difficult than it seems because Classes are also objects in ruby. (Kudos to Stephen)
class WhatIsSelf
  def test
    puts "At the instance level, self is #{self}"
  end
  def self.test
    puts "At the class level, self is #{self}"
  end
end
WhatIsSelf.test
 #=> At the class level, self is WhatIsSelf
WhatIsSelf.new.test
 #=> At the instance level, self is #<WhatIsSelf:0x28190>
This short snippet indicates two things:

at the class level, self is the class, in this case WhatIsSelf.
at the instance level, self is the instance in context, in this case the instance of WhatIsSelf at memory location 0×28190.
==================================
Understanding blocks, Procs and methods

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Understanding_blocks.2C_Procs_and_methods
==================================

Lambda?
Proc?
proc not bother about parameters, where as lambda bother..means no.of parameters are mandatory in lambda

==================================
RACK:
=====
CGI was first widely used method of running Ruby scripts on server-side. You could run it like shell, perl or python scripts inside Apache using special module. Apache and FastCGI was preffered method of deploying Rails applications, until it was replaced by solutions using HTTP proxy and a “cluster” of dedicated Ruby servers (e.g. Mongrel). When Phusion Passenger (mod_rails) arrived and started supporting Rack – we had clear winner: Rack dominated Ruby web development world.(http://amberbit.com/blog/introduction-to-rack-middleware)


Rake:
=====
Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks.

Yield in Ruby:
=============
Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.

#!/usr/bin/ruby

def test
   puts "You are in the method"
   yield
   puts "You are again back to the method"
   yield
end
test {puts "You are in the block"}
This will produce following result:

You are in the method
You are in the block
You are again back to the method
You are in the block
You also can pass parameters with the yield statement. Here is an example:

#!/usr/bin/ruby

def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}
This will produce following result:

You are in the block 5
You are in the method test
You are in the block 100

=======================================
Ruby's yield statement gives control to a user specified block from the method's body.
class NumericSequences
   def fibo(limit)
     i = 1
     yield 1
     yield 1
     a = 1
     b = 1
     while (i < limit)
         t = a
         a = a + b
         b = t
         yield a
         i = i+1
     end
  end
  ...
end



The fibo method can be used by specifying a block that will be executed each time the control reaches a yield statement. For example:
capistrano  deployment:    http://guides.beanstalkapp.com/deployments/deploy-with-capistrano.html


irb(main):001:0> g = NumericSequences::new
=> #<NumericSequences:0xb7cd703c>
irb(main):002:0> g.fibo(10) {|x| print "Fibonacci number: #{x}\n"}
Fibonacci number: 1
Fibonacci number: 1
Fibonacci number: 2
Fibonacci number: 3
Fibonacci number: 5
Fibonacci number: 8
Fibonacci number: 13
Fibonacci number: 21
Fibonacci number: 34
Fibonacci number: 55
Fibonacci number: 89
=======================
include : mixes in specified module methods as instance methods in the target class
extend : mixes in specified module methods as class methods in the target class

lamda vs proc: http://techspry.com/ruby_and_rails/proc-and-lambda-in-ruby/

application server vs web server?


  ruby 1.9.2:
  ===========
  http://nuclearsquid.com/writings/ruby-1-9-what-s-new-what-s-changed/
>> ?c
=> "c"

>> "ruby"[1]
=> "u"

>> i = 0
=> 0
>> [1,2,3].each{|i|}
=> [1, 2, 3]
>> i
=> 0

NEW:
>> {:a => "b"}
=> {:a=>"b"}
>> {a: "b"}
=> {:a=>"b"}

>> (1..10).to_a.inject(:+)
=> 55


>> enum = (1..4).to_enum
=> #<Enumerator:0x1344a8>
>> enum.each{|i| puts i}
1
2
3
4
=> 1..4
>> enum.next
=> 1
>> enum.next
================
============
    a = "cruel world"
    a.scan(/\w+/)        #=> ["cruel", "world"]
    a.scan(/.../)        #=> ["cru", "el ", "wor"]
    a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
    a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

============
    SEND:
    Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

    class Klass
      def hello(*args)
        "Hello " + args.join(' ')
      end
    end
    k = Klass.new
    k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"


=================

 Q)Collect vs Map in ruby?

A)=>collect is recommended to be used when the list is not changed:
  => ruby-1.8.7-p302 :009 > ["one", "two", "three"].collect{|item| item.length == 3}
  =>[true, true, false]

=>map is recommended to be used when the elements of the list have to be processed:
  ["one", "two", "three"].map{|item| process(item)}

  ============
  Q)Differences between lambda and Proc. I know of two distinctions?
  A)=>http://anilgalve.blogspot.in/2011/09/block-vs-lambda-vs-proc-what-is-block.html
  temp_proc = Proc.new {|a,b| puts "sum is #{a + b}" }
  temp_lambda = lambda {|a,b| puts "sum is #{a + b}" }
  temp_lambda.call(2,3) #5
  temp_lambda.call(2) #wrong number of arguments error
  temp_lambda.call(2,3,4) #wrong number of arguments error
  temp_proc.call (2,3) # 5
  temp_proc.call (2)
  # nil can't be coerced. Since the second parameter was not supplied,
  # proc.call supplied nil for the missing parameter
  temp_proc.call(2,3,4) #5
  =>First difference is that lambda.call wants the exact number of parameters to be supplied. Otherwise lambda will throw “wrong number of arguments error”. While Proc doesn’t demand that. For the missing params proc will supply “nil” and any extra parameter is ignored.

  =>Second difference has to do with the usage of the word “return” in the context of proc. When there is a return keyword inside the block then proc treats that statement as returning from the method. Hence the statement return “inside method learning_proc” was never executed. Lambda behaves the way ruby behaves in general. The control goes to the next statement after the temp_lambda.call is finished.
    def learning_proc
      temp_proc = Proc.new { return "creating proc" }
      temp_proc.call # control leaves the method here
      return "inside method learning_proc"
    end

    puts learning_proc

    def learning_lambda
      temp_lambda = lambda { return "creating lambda" }
      temp_lambda.call # control doesn't leave the method here
      return "inside method learning_lambda"
    end
    ============
    Q)yield?
    A)=>http://anilgalve.blogspot.in/2011/09/block-vs-lambda-vs-proc-what-is-block.html

    ============
    Q)differences between Require, Load, Include and Extend methods?
    A) http://anilgalve.blogspot.in/2011/09/ruby-require-vs-load-vs-include-vs.html

    ============
    Q)The Difference Between Ruby Symbols and Strings?
    Mutable objects(string) can be changed after assignment while immutable(symbol) objects can only be overwritten.

==============
    Private:
    http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/
    we can call a private method from within a class it is declared in as well as all subclasses of this class e.g.
    class A
      def main_method
        method1
      end

      private
      def method1
        puts "hello from #{self.class}"
      end
    end

    class B < A
      def main_method
        method1
      end
    end

    A.new.main_method
    B.new.main_method



    However, as soon as we try to use an explicit receiver, even if the receiver is "self", the method call will fail e.g.
    class C < A
      def main_method
        self.method1
      end
    end

    C.new.main_method

    Protected:
    Protected methods are also a little different. You can always call a protected method with an implicit receiver, just like private, but in addition you can call a protected method with an explicit receiver as long as this receiver is self or an object of the same class as self. Let's modify our example above and make the method protected:
============
    SUPER:
    super calls a parent method of the same name, with the same arguments." An unadorned super calls them with the same arguments. There's nothing that says the child can't pass a subset of the parameters to the parent if that's what the parent takes
    =>When you invoke super with no arguments Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. It automatically forwards the arguments that were passed to the method from which it's called.
    Called with an empty argument list - super()-it sends no arguments to the higher-up method, even if arguments were passed to the current method.
    Called with specific arguments - super(a, b, c) - it sends exactly those arguments.


    class Bicycle
      attr_reader :gears, :wheels, :seats
      def initialize(gears = 1)
        @wheels = 2
        @seats = 1
        @gears = gears
      end
    end

    class Tandem < Bicycle
      def initialize(gears)
        super
        @seats = 2
      end
    end
    t = Tandem.new(2)
    puts t.gears
    puts t.wheels
    puts t.seats
    b = Bicycle.new
    puts b.gears
    puts b.wheels
    puts b.seats

    The output is:

    >ruby p038bicycle.rb
    2
    2
    2
    1
    2
    1
    ============
    ClassName.method vs self.method?
    =>def before_create self.hashed_password = User.hash_password(self.password) end

    In this example, User.hash_password calls the hash_password method on the class User, whereas self.hashed_password= calls the hashed_password= method on this particular instance of User.

    If you replace User.hash_password with self.hash_password, Ruby would complain with a NoMethodError, because no instance method by the name of hash_password exists in the class User. You could replace it with self.class.hash_password, though.

    If you replace self.hashed_password= with simply hashed_password=, Ruby would create a local variable named hashed_password, rather than call the instance method hashed_password=. You need to explicitly add self if you want to call attribute writers.

    The self in the method definition (def self.hash_password) makes hash_password a class method instead of an instance method. In this context, self refers to the class. In the context of an instance method, self refers to an instance
============
    CRUD vs REST:
    http://programmers.stackexchange.com/questions/120716/difference-between-rest-and-crud
============
    attr_accessor vs attr_accessible ?
    http://maxivak.com/attr_accessor-vs-attr_accessible-ruby-on-rails/
    =>attr_accessor is used to generate getter and setter methods.
    =>attr_accessible (documentation) says "the specified attributes are accessible and all others are protected" (think of it as whitelisting.)

    whereas

    =>attr_protected (documentation) says "the specified attributes are protected and all others are accessible" (think of it as blacklisting.)

    A protected attribute is one that can only be modified explicitly (e.g. via attribute=) and can't be updated via mass assignment (e.g. using model.update_attributes or by passing attributes to new). The behaviour upon an attempt to update a protected attribute via mass assignment depends on the mass_assignment_sanitizer setting (see the update below).

    The classic example would be if a User model had an is_admin attribute you could protect that attribute to prevent form submissions that would allow any user to be set as an administrator.

    (OR)
    attr_accessor is a ruby method that makes a getter and a setter. attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or up update_attributes(attrs).

    Here's a mass assignment:

    Order.new({ :type => 'Corn', :quantity => 6 })
    You can imagine that the order might also have a discount code, say :price_off. If you don't tag :price_off as attr_accessible you stop malicious code from being able to do like so:

      Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })
      Even if your form doesn't have a field for :price_off, if it's in your model it's available by default. This means a crafted POST could still set it. Using attr_accessible white lists those things that can be mass assigned.

      (OR)
    attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

      attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.

============
        flass message if request is Ajax?
        http://www.whatcodecraves.com/articles/2008/12/13/rails-flash-with-ajax
        http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
============
        jquery's bind vs live vs delegate methods?
        http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
============
        yield vs proc vs lambda?
        http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

============

        send vs eval vs call? and call private method using send and  method_object?
        http://khelll.com/blog/ruby/ruby-dynamic-method-calling/

        In ruby you can call a public instance method directly ,ex :
        s= "hi man"
        p s.length #=> 6
        p s.include? "hi" #=> true

        =>send
        One way to invoke a method dynamically in ruby is to send a message to the object:
        p s.send(:length) #=> 6
        p s.send(:include?,"hi") #=> true

        =>call
        A second way is instantiate a method object and then call it:
          method_object = s.method(:length)
          p method_object.call #=> 6
          method_object = s.method(:include?)
          p method_object.call('hi')  #=> true

          =>eval
          eval "s.length" #=> 6
          eval "s.include? 'hi'" #=>true


          class Foo
            private
            def hi
              puts "hi man"
            end
          end

          # Normal method calling
          f = Foo.new  #=> <Foo:0x10a0d51>
          f.hi  #=>NoMethodError: private method `hi' called for #<Foo:0x10a0d51>

          # Sending a message
          f.send :hi #  hi man

          # Instantiating a method object
          f.method(:hi).call  # hi man

          # Using eval
          eval "f.hi"  #=>NoMethodError: private method `hi' called for #<Foo:0x10a0d51>

          # Using instance_eval
          f.instance_eval {hi}  # hi man

==========


RUBY2.0 FEATURES:
================
Keyword arguments
%i and %I symbol array literal
Refinements
Module#prepend
Unbound methods from a module can be bound to any object
const_get understands namespaces
#to_h as standard for ‘convert to hash’
Array#bsearch and Range#bsearch
Enumerable#lazy
Lazy Enumerator#size and Range#size
Rubygems Gemfile support
RDoc markdown support
Use warn like puts
Logger compatible syslog interface
TracePoint
Asynchronous Thread interrupt handling
Garbage collection improvements
ObjectSpace.reachable_objects_from
Optimised backtrace
Zlib streaming support
Multithreaded Zlib processing
Default UTF-8 encoding
Binary string shortcut
String#lines, #chars, etc return an Array
__callee__ returns the method as called
RegExp engine is changed to Onigmo
Hash#default_proc= now accepts nil
Option for File.fnmatch? to expand braces
Shellwords calls #to_s on arguments
system and exec now close non-standard file descriptors by default
Protected methods treated like private for #respond_to?
#inspect no longer calls #to_s
LoadError#path
Process.getsid
Error on trapping signals used internally
True thread local variables
Better error on joining current/main thread
Mutex changes
Custom thread and fiber stack sizes
Stricter Fiber#transfer
RubyVM::InstructionSequence
ObjectSpace::WeakMap
Top level define_method
No warning for unused variables starting with _
Proc#== and #eql? removed
ARGF#each_codepoint
Time#to_s
Random parameter of Array#shuffle! and #sample now called with max arg
CGI HTML5 tag builder
CSV::dump and ::load removed
Iconv removed
Syck removed
io/wait
Net::HTTP performance improvements
Net::HTTP can specify the host/port to connect from
OpenStruct can act like a hash
Timeout support in Resolv



ALL TIME ZONES:
==============
require 'active_support/time_with_zone'
ActiveSupport::TimeZone.zones_map.values





Duck Typing:
===========
def print_even_or_odd(collection)
  collection.each do |item|
    puts "#{item} is #{item.even? ? "even" : "odd"}."
  end
end


OR

In computer programming with object-oriented programming languages, duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see history below), which may be phrased as follows:

class Duck
  def quack
    puts "Quaaaaaack!"
  end

  def feathers
    puts "The duck has white and gray feathers."
  end
end

class Person
  def quack
    puts "The person imitates a duck."
  end

  def feathers
    puts "The person takes a feather from the ground and shows it."
  end
end

def in_the_forest(duck)
  duck.quack
  duck.feathers
end

def game
  donald = Duck.new
  john = Person.new
  in_the_forest donald
  in_the_forest john
end

game


Ruby is pass by value:
=====================
def foo(bar)
  bar = 'reference'
end

baz = 'value'

foo(baz)

puts "Ruby is pass-by-#{baz}"
# Ruby is pass-by-value




Proc vs lamda in ruby:
=====================
The are two major difference between procs and lambda

1.) A proc can break the parent method, return values from it, and raise exceptions, while such statements in lambda will only affect the lambda object.


def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo"
end

def bar
  f = lambda { return "return from lambda" }
  f.call # control does not leave bar here
  return "return from bar"
end

puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"

2.) The other difference is unlike Procs, lambdas check the number of arguments passed.

def some_method(code)
  one, two = 1, 2
  code.call(one, two)
end

some_method(Proc.new{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

some_method(lambda{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

# => First argument: 1 and  and Second argument 2 and Third argument NilClass
# *.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError)

We see with the Proc example, extra variables are set to nil. However with lambdas, Ruby throws an error instead.



Ruby 1.9:
========
One area where 1.9 can be slower than 1.8 is string handling.

Fiber:
======
fib = Fiber.new do
   x, y = 0, 1
   loop do
    Fiber.yield y
    x,y = y,x+y
   end
  end
  20.times { puts fib.resume }

  The code prints out the first 20 Fibonacci numbers. The concept it uses is called Coroutine. Basically, invoking Fiber.yield call stops ("suspends") execution of this code (don't confuse it with yield used for executing blocks). If you're familiar with debuggers, imagine hitting "suspend" on a thread or seeing the thread hit a breakpoint. fib is a handle to this Fiber, and can be used to manipulate it. The fib.resume call in line 8, does exactly what it says: it resumes the execution of the Fiber's code with the statement after the Fiber.yield call.

Line 4 shows Fiber.yield called with a parameter y. In a way, this can be thought of as similar to return y. The difference between a subroutine's return and a coroutine's Fiber.yield is what happens to the context of the code after the call. return means that, say, a function call's activation frame (or stack frame) is deallocated, which means all local variables are gone. With a Coroutine, yielding keeps the activation frame and all the data therein alive, so the code can use it when it'sresumed later.

Now it becomes clear how the code works: it's just a loop that iteratively calculates one Fibonacci number after the other. Once it's done with one, it suspends itself, giving someone else the control of the CPU. When that code wants the next number in the sequence, it simply resumes the Fibonacci code, which runs another iteration and then hands off control (and the next Fibonacci number) by suspending itself with Fiber.yield


Fast Performance:
================
def bench
  start = Time.now
  1000000.times do
    yield
  end
  puts Time.now - start
end

puts "Test 1: do things"
bench {
  "yeho!12".next
  rand(100)
  i ||= 1
  i = i + 1
}

puts "Test 2: \"stuff\""
bench {
  "stuff"
}

puts "Test 3: 'stuff'"
bench {
  'stuff'
}

puts "Test 4: :stuff"
bench {
  :stuff
}

$time spec spec


Encoding/Unicode:
================
Encoding.name_list
Encoding.aliases
===========

Monkey Patch:
============
http://www.runtime-era.com/2012/12/reopen-and-modify-ruby-classes-monkey.html
->a way to extend or modify the runtime code of dynamic languages [...] without altering the original source code.
->Re-opening existing classes to change or add to their behavior. For example, if I have always felt that Array should implement the sum method, I can add it in my codebase:

cReopen and Add to Any Class
This type of modification can be done to any class in Ruby. This includes Gems and core Ruby classes. Let's say I wanted to be able to (naively) sum elements in my Arrays:

[1,2,3,4].sum
# undefined method `sum' for [1, 2, 3, 4]:Array (NoMethodError)

class Array

  def sum
    sum = 0
    self.each do |e|
      sum += e
    end
    sum
  end

end

[1,2,3,4].sum
# 10
=================

Proc vs Lambda?
==============
1. Proc doesn't check the parameters passed, but lambda does

2. Proc returns from the calling method, while lambda doesn't

 def meth1
   Proc.new { return 'return from proc' }.call
   return 'return from method'
 end

 puts meth1
 => return from proc

 def meth2
   lambda { return 'return from lambda' }.call
   return 'return from method'
 end

 puts meth2
 => return from method
If they are not called inside a method,

 proc1 = Proc.new { return "Thank you" }

 proc1.call
 => LocalJumpError: unexpected return

 lambda1 = lambda { return "Thank you" }

 lambda1.call
 => "Thank you"
===============

No comments:

Post a Comment