Saturday, 7 December 2013

Javascript and Jquery


http://www.learningjquery.com/2006/09/introducing-document-ready

   


JQUERY:
http://jqueryui.com/demos/
http://try.jquery.com/levels/1/challenges/3
http://coding.smashingmagazine.com/2012/05/31/50-jquery-function-demos-for-aspiring-web-developers/

========================
Simple Ajax call
-----------------
Note: Unable to call $(this) inside ajax so use local variable to access

  $('.make_fav').click(function(){
    var v_id=$(this).attr('id');
    var th = this  // create local var for THIS
    $.ajax({
        dataType: 'json',  // not jsonp
        url: "/favo",
        type: "get",
        data: { id : v_id }, // passing argument to the action
        success: function(response) {
          console.log(response.active)      // based on response change the class
            if (response.active==false){
              $(th).addClass('fav_ajax')
              $(th).removeClass('unfav_ajax')
            }else{
              $(th).addClass('unfav_ajax')
              $(th).removeClass('fav_ajax')
            }
        }
    });

  })
===========================
=>What is prototype property in javascript?
To add new attribute to an object
object.prototype.name=value
ex: user.prototype.age = 28  #when there is no age.

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

General Info


general info:
-------------
http://www.xe.com/ucc/         ===========>currency converter
http://www.kurnoolcity.com/       ==========>kurnool city passport
http://www.ap.nic.in/passport/APP-Coll.htm
http://lanyrd.com/2011/gogaruco/shmhw/  ==>videos for testing
site id's:
----------
->alaramanaiah/aug1985  =====>basecamp


:pserver:ramana@122.183.217.135:2401/Sayagame      ====> SAYAGAME CHECKOUT

RAILS_ENV=stage rake db:migrate



http://stage-stutalk.heroku.com/user

paypal sandbox =============>https://developer.paypal.com/cgi-bin/devscr?cmd=_logout


http://git-scm.com/        ==========>git site( repository)
alaramanaiah@dckap.com,58aanamar



http://www.ipadpeek.com/                ============>ipad simulator
http://iphonetester.com/


http://www.tutorialized.com/view/tutorial/Develop-iPhone-apps-using-Ruby-on-Rails/36116

iphone applicaions using ruby on rails


general:
---------
Virus – Vital Information Resources Under Seize.

NASA – National Aeronautics Space Administration

ISRO – Indian Space Research Organisation

Computer – Commonly Operating Machine Particularly Used for Technology Entertainment and Research

Google - Global Organization of Oriented Group Language of Earth
http://122.183.217.145/sayagame/faq.html     =====>sayagame
amazon login Username: webdev@stutalk.com Password: StuAMAZ11

BLOGS FOR rubyonrails:
=====================
1)stackoverflow
2)railscasts/asciicasts
3)rubygems
4)edgeguides
5)api.rubyonrails.org
6)rorexperts
7)github
8)rails google groups
9)railsforum
10)rubyforge
11)rails.nuvvo.com
12)allinterview.com
13)rubyinside.com
14)rubyflow.com
15)gems.github.com
16)rails.rubyonrails.org
17)ruby.railstutorial.org

Server


Nginx server ip's & errors statistics:
=========================
=> tail -f /mnt/errors/access.log | ngxtop top remote_addr => Shows IP'S list of users
=> ngxtop -i 'status >= 502' print request status http_referer -l /mnt/errors/access.log =>Shows for which pages we get 502 error
=>ngxtop -l /mnt/errors/access.log => Shows all types of errors from log




=>configure mongrel_cluseter?
Set up a mongrel cluster
Configure 2 or three ports for the mongrel cluster
Create a map file for my random load balancer
Set up a way to restart the cluster if the server reboots
Configure Apache to forward requests to the mongrel cluster
Configure capistrano to deploy the application.
================================
=>How can you generate sitemaps for your Rails site?
You can use dynamic_sitemaps gem to generate sitemaps
How can you show search user friendly urls instead of using only numeric ids?
The simplest way to do this is to use the gem FriendlyID.
It gives you the ability to specify a friendly URL for pages so that instead of the standard page URLs like:
http://mysite.com/page/1
You can build pages such as:
http://mysite.com/page/my-awesome-page-about-articles-and-content
How can you create page titles and metadata for your pages?
You can use the Headliner plugin for adding page titles.
You can use the MetaMagic plugin to add meta tags.
How can you create breadcrumbs on your pages?
Gretel is a great plugin to introduce breadcrumbs in your Rails application.
Another very simple implementation is breadcrumb_on_rails.
Architecture Related Questions
This questions can be from different angles like: quality, security, scalability, manageability, interoperability, reusability and all the other ilities you name! Here are a few example questions:
Is Rails scalable?
Yes Rails gives you complete freedom to use all traditional means of scaling an application. Things like memcached, caching full pages, caching fragments are all supported.
You can use any standard CDN to serve your media and static content as well.
Database scaling using sharding is supported.
Finally heroku makes your life easier by giving you the flexibility to scale up/down based on your need. Mostly websites have a peak time during which you need more servers and then there is a sleep time. Heroku makes that on-demand scaling process simpler. Companies such as HireFireApp.com makes the autoscale process easier.
============================================
=>How can you safeguard a rails application from SQL injection attack?
User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
 SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1

  User.where("login = ? AND password = ?", entered_user_name, entered_password).first
 User.where(:login => entered_user_name, :password => entered_password).first

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




create branch in heroku:
{from git
commit all changes to current branch => authenticaion

move changes to from git to heroku:
gem install heroku
heroku login
heroku create qjitsu-staging
git push heroku authentication:master
git remote add heroku git@heroku.com:qjitsu-staging.git
heroku keys
heroku keys:remove ramanaa85@mail.com


remove branch in local:
$ git branch -D branch_name

remove branch which is in remote:
$git push origin :branch_name
$git remote prune origin

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


ruby by satishtalim:
http://rubylearning.com/satishtalim/ruby_overriding_methods.html
paperlicp:
http://gkunwar1.wordpress.com/2012/06/25/how-to-upload-file-using-paperclip-in-rails/


HAML:
http://haml.info/docs/yardoc/file.REFERENCE.html


**Ubuntu on windows7 with VMWare:
=>  http://www.howtogeek.com/howto/11287/how-to-run-ubuntu-in-windows-7-with-vmware-player/
=>  http://linux.softpedia.com/get/System/Operating-Systems/Linux-Distributions/Ubuntu-Precise-Pangolin-76997.shtml


capistrano:
https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started

rspec testing:
http://spitfiresky.com/blog/how-you-should-be-doing-testing-in-rails.html
http://railsapps.github.io/tutorial-rails-devise-rspec-cucumber.html

javascriptclient side validations:
http://webtempest.com/easy-client-side-form-validation-for-rails-3-1/

javascript client side validations:
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

**mobile application development:
http://www.tobiascohen.com/articles/2012/07/01/creating-a-mobile-version-of-your-rails-site/
http://stackoverflow.com/questions/5126085/ruby-on-rails-mobile-application/5130756#5130756

basics => http://www.rubyinside.com/21-ruby-tricks-902.html

authentication =>http://rubysource.com/rails-userpassword-authentication-from-scratch-part-ii/

aptana: http://www.pixelite.co.nz/article/installing-aptana-ubuntu-1204




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

=>google api key:
https://code.google.com/apis/console/#project:300004415644:access
http://railscasts.com/episodes/241-simple-omniauth?view=asciicast (omniauth-twitter)

twitter api key
https://dev.twitter.com/apps/4355889/show

facebook:
https://developers.facebook.com/apps/515338231858750/summary?save=1
================
=>Why rails slow?

Rails applications can run slowly for few fundamental reasons. The first is simple: Rails makes assumptions for you to speed up development. Usually, these assumptions are correct and helpful. They are not always beneficial for performance, however, and they can result in an inefficient use of resources — particularly database resources.
For example, ActiveRecord selects all fields on a query by default, using a SQL statement equivalent to SELECT *. In situations with a large number of columns — particularly if some are large VARCHAR or BLOB fields — this behavior can be a significant problem in terms of memory usage and performance.
Another significant challenge is the N+1 problem, which this article examines in detail. Essentially, this results in many small queries being performed, rather than one large query.ActiveRecord has no way to know that, for example, a child record is being requested for each of a set of parent records, so it will produce one child record query for each parent record. Because of per-query overhead, this behavior can cause significant performance issues.
==================

=>google api key:
https://code.google.com/apis/console/#project:300004415644:access
http://railscasts.com/episodes/241-simple-omniauth?view=asciicast (omniauth-twitter)

twitter api key
https://dev.twitter.com/apps/4355889/show

facebook:
https://developers.facebook.com/apps/515338231858750/summary?save=1
=======================

pg_dump -C -h localhost -U postgres myapp_production | psql -h 111.22.33.44 -U postgres myapp_production

mysql dis-adv's
=>A subquery with a depth of 3 levels cannot be optimized by MySQL anymore and is executed on every row.
=> time fields do not record milliseconds
=>multiple engines and one server layer

=>postgres =>full text search good,only one server layer


New Relic for ROR performance

Ruby core concepts


=>rho mobile
http://www.slideshare.net/Anubavam/rails-to-rhomobile

=>Capistrano deployment
http://robmclarty.com/blog/how-to-deploy-a-rails-4-app-with-git-and-capistrano

=>ruby docs
http://www.ruby-doc.org/core-2.0.0/Struct.html

=>jquery questions
http://www.codeproject.com/Articles/618484/Latest-jQuery-interview-questions-and-answers

=>ruby method_missing
Ruby's define_method, method_missing, and instance_eval

=>html elements
https://developer.mozilla.org/en-US/docs/Web/HTML/Element

=>Heroku
http://railsapps.github.io/rails-heroku-tutorial.html

https://devcenter.heroku.com/articles/getting-started-with-rails4

=>Mongodb
http://docs.mongodb.org/ecosystem/drivers/ruby/

=>Turbolinks
http://geekmonkey.org/articles/28-introducing-turbolinks-for-rails-4-0

=>ruby 1.9 vs 2.0 vs 1.8
http://slideshow.rubyforge.org/ruby19.html#1

http://globaldev.co.uk/2013/03/ruby-2-0-0-in-detail/

=>facebook with koala
https://github.com/arsduo/koala




Sendmail:
=========
/sbin/service
/etc/init.d/sendmail
locate sendmail

==========================
HOSTING THE SITE:
=================
sudo gem install mongrel –include-dependencies
sudo gem install mongrel_cluster
mongrel_rails cluster::configure -p 8001 -e production -a 127.0.0.1 -N 3
mongrel_rails cluster::start
mongrel_rails cluster::status
mongrel_rails cluster::stop
mongrel_rails cluster::restart
Nginx/APACHE-load balancing and fault tolerance
Apache and Nginx can serve static files faster
Apache/Nginx will take care of distributing requests between the instances in the cluster(mongrel).
sudo mongrel_rails cluster::configure -e production -p 3010 -N 2 -c /home/corti/Documents/ror/myapp -a 127.0.0.1 --user mongrel --group mongrel
mongrel_rails cluster::configure -e production -p 8000 -N 2 -c /home/demo/public_html/railsapp -a 127.0.0.1
-N=>2 processes
-a=>127.0.0.1  (@)
-p=>ports( 3010 and 3011)
-c=> /home/corti/Documents/ror/myapp  path of the appplication
cluster= collection of ports
(http://stackoverflow.com/questions/4113299/ruby-on-rails-server-options)
webrick(ruby),mongrel(c and ruby),thin,Phusion Passenger(c++),
Phusion Passenger can start any no. of processes for you when your site becomes busy, not like mongrel only a perticular ports
Capistrano:here "deployment" refers to doing all this preparation work to run the application(is not an application server.)==>replacement for FTP
http://articles.slicehost.com/2007/9/28/ubuntu-feisty-apache-vhosts-rails-and-mongrels

==================
s/w projects developement types:
===============================
t&m =
retain = vertis(everyday 16hrs)
fixed bid = sayagame,cherry branch gallery(fixed for 80hrs)


rails deployment servers:-
========================
slicehost,kattare,capistrono,dreamhost,go-daddy,heroku,amazon s3

http://ariejan.net/2011/09/14/lighting-fast-zero-downtime-deployments-with-git-capistrano-nginx-and-unicorn   =>deployments with git, capistrano, nginx and Unicorn
https://github.com/capistrano/capistrano/wiki/2.x-From-The-Beginning =====>capistrano deployment


http://www.rorexperts.com/rvm-installation-on-ubuntu-10-04-version-t2211.html
http://stjhimy.com/posts/10-five-quick-steps-to-set-up-rvm-with-rails-2-and-rails3
http://www.rubyinside.com/rvm-ruby-version-manager-2347.html

desiga: 0011+9566655680
http://railsapps.github.com/installing-rails-3-1.html

http://telugudictionary.telugupedia.com/

http://ubuntuguide.net/install-firefox-7-stable-in-ubuntu-11-1010-0410-10 ==> to update FIREFOX browser



application controller: stop back button:
before_filter :set_cache_buster

def set_cache_buster
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end

mongrel_rails cluster::start -C /home3/s/smcampbell/public_html/nanohygienics_pr/config/mongrel/production.yml

http://www2.elc.polyu.edu.hk/CILL/speaking.htm        ==========> spoken english


http://sidorovis.blogspot.com/2011/02/ruby-gems-errnoetimedout-issue-solution.html => gem is not installing

http://www.railsecommerce.com/           ============>rails e-commerce applications

http://en.wordpress.com/tag/ruby-on-rails-ror/           -==> tuts of ror while mutiple dbs connections


http://www.slideshare.net/wycats/jquery-presentation-to-rails-developers-110063   ====> for jquery

http://www.slideshare.net/mokolabs/haml-and-sass-in-15-minutes    ========> haml and sass:video tutorails

http://rails.nuvvo.com/lesson/6380-action-controller-streaming-and-file-downloads ===> rails tutorials

http://wowkhmer.com/2011/09/19/unobtrusive-ajax-with-rails-31/          ===========>3.1 tuts,ajax
gnome-open      =>to open website

http://www.blog.bridgeutopiaweb.com/post/how-to-install-rvm-and-rails-3-on-snow-leopard/ ==>RVM

http://magicmodels.rubyforge.org/magic_multi_connections/             => multiple db connections

http://rails-erd.rubyforge.org/install.html    ==> rails E-R diagrams
rake erd orientation=horizontal title='Global Brand Assurance ERD' filename="BA_ERD_rough" indirect=true notation=bachman attributes=foreign_keys,primary_keys,timestamps,inheritance,content

http://tutorvideo.org/ =>video tutorials

https://help.ubuntu.com/community/PostgreSQL                   =====> postgresql

git repo-config --get-regexp user.    ->          ====> git command to find system username
user.name ROR Dev2
user.email deepaks@dckap.com

http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#top       ==>RUBY ON RAILS TUTORAILS



http://chat.stackoverflow.com/rooms/24/ruby-rails         =========>stack overflow chat

http://www.alfajango.com/blog/rails-3-remote-links-and-forms/  =======>rails 3.1 jquery and ajax

wine 'C:\Program Files\Internet Explorer\iexplore'      =>cmd to open ie
http://twitter.rubyforge.org/
https://dev.twitter.com/docs/tweet-button
http://www.paolocorti.net/2007/11/08/ruby-on-rails-applications-with-mongrel-clusters-and-apache-on-ubuntu/     =====>deployment
git --version     =>to find git version installed on system
http://kibyegon.wordpress.com/2010/05/13/how-to-install-git-on-ubuntu-lucid-10-04/

http://coding.smashingmagazine.com/2009/02/25/ruby-on-rails-tips/     ====>tips for ror developers
http://www.webresourcesdepot.com/23-amazing-and-open-source-ruby-on-rails-applications/ ====>
23 different ror apps(cms,crm..)

http://mashable.com/2007/09/30/ruby-on-rails-toolbox/      ====> 23 different ror apps(cms,crm..)


http://dsal.uchicago.edu/dictionaries/gwynn/            =====>telugu -to- english site

how to go for mongrel/webrick             ==============> how to decide the server

=>admin-creation :http://stackoverflow.com/questions/2708417/creating-an-admin-user-in-devise-on-rails-beta-3

http://guides.rubyonrails.org/form_helpers.html           =>ajax in guides
http://edgeguides.rubyonrails.org/ajax_on_rails.html

http://www.ultrasaurus.com/sarahblog/2009/06/simple-web-services-with-rails/        ====>webservice
http://blog.complitech.net/web-services-basics-ruby-on-rails/
https://peepcode.com/        ======>screencasts
http://www.ibm.com/developerworks/opensource/library/os-ws-rubyrails/index.html
http://railscasts.com/episodes?utf8=%E2%9C%93&search=web+service

=>developing a game with Ruby using the Gosu and Chipmunk gems
Don't cry because it's over, smile because it happened


http://changelogshow.com/             ===========> audio tutorials
http://srikanthjeeva.blogspot.com/2010/04/thinking-sphinx.html      =====>thinking-sphinx
http://railsapps.github.com/rails-heroku-tutorial.html              ===>heroku
http://peepcode.com/products/phusion-passenger       ========>phusion-passenger
http://devcenter.heroku.com/articles/rails3

crm tools for rubyonrails:
=========================
1)Fat Free            http://www.fatfreecrm.com/
2)XLsuite             http://xlsuite.org/
3)salesforce          http://www.salesforce.com/platform/cloud-infrastructure/integration.jsp
4)cohort
5)mongo




SERVER:
========
cat /etc/httpd.conf | more
cat /etc/httpd-2.2/httpd.conf | grep 10505
ps ax | grep ru
ps ax
tail -100f production.log
/home3/s/smcampbell/conf/apache2.conf
ror tuts "http://rubymonk.com/"



cms tools for rubyonrails:-
==========================
1)Radiant cms
2)Refinery cms
3)adva-cms
4)BrowserCMS
5)locomotive


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

Scalability:
===========
http://nerdfortress.com/2008/05/13/ruby-on-rails-pros-cons-lets-get-real/
= put a Nginx load balancing reverse proxy in front and then choose your framework, this allows you to add in a pretty well unlimited number of instances. If you care about hardware and electricity costs then go for a more efficient stack. The key part is intelligent cache's.


AGILE AND SCRUM:
===============
http://www.questions-interviews.com/software-development-testing-models/scrum.aspx#what_is_the_difference_between_agile_and_scrum_development


SEO (search engine optimization):
================================
Headliner for titles
Metamagic for meta tags
Gretel for breadcrumbs
FriendlyId for friendly URLs
Dynamic Sitemaps for sitemaps
- See more at: http://www.railsant.com/rails-seo-pack-5-plugins-optimize-site/#sthash.JAyRTS7P.dpuf

RSPEC


=>context vs describe?
According to the rspec source code, “context” is just a alias method of “describe”, meaning that there is no functional difference between these two methods. However, there is a contextual difference that’ll help to make your tests more understandable by using both of them.

The purpose of “describe” is to wrap a set of tests against one functionality while “context” is to wrap a set of tests against one functionality under the same state. Here’s an example

===================================
=>shared examples?
Making tests is great and you get more confident day after day. But in the end you will start to see code duplication coming up everywhere. Use shared examples to DRY your test suite up.

===================================
=>Expect vs Should syntax ?

On new projects always use the expect syntax

===================================
=>Use subject?

If you have several tests related to the same subject use subject{} to DRY them up.
BAD
it { expect(assigns('message')).to match /it was born in Belville/ }
it { expect(assigns('message').creator).to match /Topolino/ }
GOOD
subject { assigns('message') }
it { should match /it was born in Billville/ }
===================================
=>Automatic tests with guard?

Running all the test suite every time you change your app can be cumbersome. It takes a lot of time and it can break your flow. With Guard you can automate your test suite running only the tests related to the updated spec, model, controller or file you are working at.

GOOD
bundle exec guard
====================================
=>Stubbing HTTP requests?

Sometimes you need to access external services. In these cases you can't rely on the real service but you should stub it with solutions like webmock.

GOOD
context "with unauthorized access" do
  let(:uri) { 'http://api.lelylan.com/types' }
  before    { stub_request(:get, uri).to_return(status: 401, body: fixture('401.json')) }
  it "gets a not authorized notification" do
    page.driver.get uri
    expect(page).to have_content 'Access denied'
  end
end
===========================================
=>Useful formatter?

Use a formatter that can give you useful information about the test suite. I personally find fuubar really nice. To make it work add the gem and set fuubar as default formatter in your Guardfile.

GOOD
# Gemfile
group :development, :test do
  gem 'fuubar'
===========================================
=>mock vs stub?
Both mock and stub are aliases of the more generic double. Like context and describe, they can be used interchangeably to make the intent of the specs more clear. This is described in a lot more detail in The RSpec Book.
================


cucumber vs rspec?
http://stackoverflow.com/questions/1700970/tdd-bdd-rails-cucumber-rspec-duplication
http://stackoverflow.com/questions/11762245/whats-the-difference-between-rspec-and-cucumber

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

HTML


NEW TAGS IN HTML5:
==================
<article>New Defines an article
<aside>New Defines content aside from the page content
<audio>New Defines sound content
<bdi>New Isolates a part of text that might be formatted in a different direction from other text outside it
<canvas>New Used to draw graphics, on the fly, via scripting (usually JavaScript)
<command>New Defines a command button that a user can invoke
<datalist>New Specifies a list of pre-defined options for input controls
<details>New Defines additional details that the user can view or hide
<embed>New Defines a container for an external application or interactive content (a plug-in)
<figcaption>New Defines a caption for a <figure> element
<figure>New Specifies self-contained content
<footer>New Defines a footer for a document or section
<header>New Defines a header for a document or section
<hgroup>New Groups heading (<h1> to <h6>) elements
<keygen>New Defines a key-pair generator field (for forms)
<mark>New Defines marked/highlighted text
<meter>New Defines a scalar measurement within a known range (a gauge)
<nav>New Defines navigation links
<output>New Defines the result of a calculation
<progress>New Represents the progress of a task
<rp>New Defines what to show in browsers that do not support ruby annotations
<rt>New Defines an explanation/pronunciation of characters (for East Asian typography)
<ruby>New Defines a ruby annotation (for East Asian typography)
<section>New Defines a section in a document
<source>New Defines multiple media resources for media elements (<video> and <audio>)
<summary>New Defines a visible heading for a <details> element
<time>New Defines a date/time
<track>New Defines text tracks for media elements (<video> and <audio>)
<video>New Defines a video or movie
<wbr>New Defines a possible line-break


Global Attributes:
==================

contenteditableNew Specifies whether the content of an element is editable or not
contextmenuNew Specifies a context menu for an element. The context menu appears when a user right-clicks on the element
draggableNew Specifies whether an element is draggable or not
dropzoneNew Specifies whether the dragged data is copied, moved, or linked, when dropped
hiddenNew Specifies that an element is not yet, or is no longer, relevant
spellcheckNew Specifies whether the element is to have its spelling and grammar checked or not




Not in HTML5:
======================
<acronym>
<applet>
<basefont>
<big>
<center>
<dir> Not supported in HTML5
<font> Not supported in HTML5
<frame> Not supported in HTML5
<noframes> Not supported in HTML5
<frameset> Not supported in HTML5
<strike>
<tt>

Errors


==>E)NameError in CategoriesController#index
uninitialized constant ApplicationController
A) application.rb to application_controller.rb


==>ActiveRecord::RecordNotFound in ProductsController#show
Couldn't find Product with ID=nw
A)url problem



200..399 - Valid response, no exception (other than 301, 302)

301, 302 - ActiveResource::Redirection

400 - ActiveResource::BadRequest

401 - ActiveResource::UnauthorizedAccess

403 - ActiveResource::ForbiddenAccess

404 - ActiveResource::ResourceNotFound

405 - ActiveResource::MethodNotAllowed

409 - ActiveResource::ResourceConflict

410 - ActiveResource::ResourceGone

422 - ActiveResource::ResourceInvalid (rescued by save as validation errors)

401..499 - ActiveResource::ClientError

500..599 - ActiveResource::ServerError

Other -
=======
=>ActiveResource::ConnectionError

=>You have a nil object when you didn't expect it!

Database


=>Diff b/w myisam and innodb

Myisam:(befor 5.5.5 default engine for mysql)
      Table level locking
      No ordering in storage of data
      Not *ACID compliant,no foreign key support and non-transactional
      reading records fast

Innodb:(default as of 5.5.5)
      Row level locking
      Row data stored in pages in PK order
      *ACID compliant and hence fully transactional with ROLLBACK and COMMIT and support for Foreign Keys
      reading records slow
ALTER TABLE <table-name> ENGINE=INNODB;    
==================================
=>Diff b/w primary key vs unique key?
A primary key must be unique.

A unique key does not have to be the primary key - see candidate key.

That is, there may be more than one combination of columns on a table that can uniquely identify a row - only one of these can be selected as the primary key. The others, though unique are candidate keys.

 there can be only one primary key for a given table, while there can be many unique keys.

 primary key cannot be NULL

 ====================================
 =>diff b/w mysql and postgresql?
 dates format different

mysql:
 #comment
 "
 case insensitive
 Only follows some of the ANSI SQL standards
 Faster
 No Foreign key support
 No Sub-selects
 Transactions  with innodb engine only


 postgresql:
 -- comment(ANSI standard)
 '
 case sensitive
 Slower
 Closer to ANSI SQL standard
 Have Foreign key support
 Have Sub-selects
 Have Transactions support
 ==========================
 =>rdbms vs nosql?
=RDBMS is completely structured way of storing data.NoSQL databases also have a structure to store data, but these structures are less strict as relational schema, so it became a better choice to some applications.
= the amount of data stored mainly depends on the Physical memory of the system. While in the NoSQL you don't have any such limits as you can scale the system horizontally.
=It's important to say that NoSQL databases are a complement in database field, and not a replacement for RDBMS.
=Graph Databases is also a very popolar NoSQL database. . Examples of the popular graphical database are Neo4j,
= OrientDB, InfiniteGraph, AllegroGraph etc.
=Facebook uses open sources the Cassandra
=NoSQL stands for "Not only SQL"
=E.g. graph databases like Neo4j, document databases like CouchDB and object databases like db4o.
=================================


   
postgresql?
https://help.ubuntu.com/8.04/serverguide/postgresql.html
http://www.thegeekstuff.com/2009/04/15-practical-postgresql-database-adminstration-commands/
 $sudo su postgres
 $psql
 $\l =>lists all databases
 $\c =>switch database
 $select current_database();

 $ CREATE USER alaramana WITH password 'password';
 $ CREATE DATABASE mydb WITH OWNER alaramana
============
===========
Install mysql?
sudo apt-get install libmysqlclient-dev, mysql-server, mysql-client
============

install sqlite3?
sudo apt-get install sqlite3 libsqlite3-dev
sudo gem install sqlite3-ruby

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

postgresql backup
=================
 $ pg_dump mydb > db.sql #To dump a database called mydb into a SQL-script file:
 $ psql -d newdb -f db.sql  #To reload such a script into a (freshly created) database named newdb:
============================
join vs include in sql?
=>The difference between joins and include is that using the include statement generates a much larger SQL query loading into memory all the attributes from the other table(s).
For example, if you have a table full of comments and you use a :joins => users to pull in all the user information for sorting purposes, etc it will work fine and take less time than :include, but say you want to display the comment along with the users name, email, etc. To get the information using :joins, it will have to make separate SQL queries for each user it fetches, whereas if you used :include this information is ready for use.

:joins returns read-only objects, :includes does not

:joins uses inner join, :includes uses outer join.

the main reason of :includes is eager loading, to avoid the N+1 problem of loading in attributes of each object using a separate query.
=============

POSTGRESQL:
===========
https://help.ubuntu.com/community/PostgreSQL
https://help.ubuntu.com/8.04/serverguide/C/postgresql.html

==================
mysql engine
SELECT table_schema,engine FROM information_schema.tables WHERE table_name='resources';


$mysql> SELECT * FROM mysql.user;      ==>to find list of users for mysql database
http://www.pantz.org/software/mysql/mysqlcommands.html    ======>mysql commands



postgresql:
===========
http://olmonrails.wordpress.com/2008/08/12/switching-rails-to-postgresql/
sudo -u postgres psql
\l
=>To find list of db's
\connect <database_name>         ==>to switchover to another database

sudo su
su postgre
psql


========
Rename mysql database name:
mysqldump -u username -p -v olddatabase > olddbdump.sql
mysqladmin -u username -p create newdatabase
mysql -u username -p newdatabase < olddbdump.sql

NoSQL and MONGODB


MONGOID VS MONGOMAPPER ?

Mongoid is completely Rails 3 compatible, and uses ActiveModel all
over the place (validations, serialization, etc), where MongoMapper is still focused on Rails 2 and uses the validatable gem for its validations.
Mongoid officially supports and works on Ruby 1.8.7, 1.9.1, and 1.9.2 head.
Mongoid supports embedded documents more robustly, performing the MongoDB atomic operations on any area of the hierarchy internally. ($set, $push, $pull, etc). With MM you need to explicitly tell it to do these operations.
MongoMapper has better relational association support and works like this as default.
MongoMapper is more extensible, with a plugin architecture that makes it pretty easy for people to extend it with their own libraries. Mongoid does not have this.
MM supports identity maps, Mongoid does not.
MM has a larger community, and probably more 3rd party library support. I went crazy on documentation and rdoc.
Mongoid supports Master/Slave replication clusters. (Writes to master, round robin reads to slaves) MM does not.
Mongoid has an extremely rich ARel style criteria API, MM use AR2 style finders. (Ed: This may not be such a big issue in MM's case since version 0.8 added a new query DSL.)
The biggest comment I have gotten from people, and why I designed Mongoid the way I did is predictability. For one, wrapping the driver cursor when dealing with huge documents and lots of them (in the millions) needs to have predictable performance and memory consumption. We noticed MM didn't deal with large documents (over 500k in size) very well as far as these characteristics go, but handles small documents better than Mongoid. (This may have changed over the past few months, but was an issue for us and others I have talked to.)


=>mongodb is server
=>mongo is shell
=>default port no. 27017
$mongo  #=> enter the mongo console
$show dbs #=> see the list of available dbs
$use my_database #=> switch to your database
$db.table_name.getIndexes() #=> replace table_name with your's

$db  => to find current database
$show collections       =>to list all collections
db.tablename.find;
db.tablename.find();

http://docs.mongodb.org/manual/tutorial/getting-started/#create-a-collection-and-insert-documents
http://stackoverflow.com/questions/2124274/mongodb-what-to-know-before-using
http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-parent-references/
http://railskey.wordpress.com/2011/10/23/mongodb-queries/
http://stackoverflow.com/questions/14849104/find-the-list-of-list-of-indexed-keys-in-mongomapper


Start mongo server:

sudo rm /var/lib/mongodb/mongod.lock  
sudo -u mongodb mongod -f /etc/mongodb.conf --repair
sudo service mongodb start










s

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"
===============