Thursday, 23 October 2014

What is the difference between collect,select, reject and inject in ruby?

What is the difference between collect,select, reject and inject in ruby?

     Some of the most commonly used Enumerable  iterators are the rhyming methods collect , select , reject , and inject .

       The collect  method (also known as map ) executes  its associated block for each element of the enumerable object, and collects the return values of the blocks into an array:
                 squares = [1,2,3].collect {|x| x*x} # => [1,4,9]

        The select  method invokes the associated block for each element in the enumerable
object, and returns an array of elements for which the block returns a value other than false  or nil . For example:
                 evens = (1..10).select {|x| x%2 == 0} # => [2,4,6,8,10]

        The reject  method is simply the opposite of select ; it returns an array of elements for
which the block returns nil  or false . For example:
                odds = (1..10).reject {|x| x%2 == 0} # => [1,3,5,7,9]

          The inject  method is a little more complicated than the others. It invokes the associated
block with two arguments. The first argument is an accumulated value of some sort from previous iterations. The second argument is the next element of the enumerable object. The return value of the block becomes the first block argument for the next iteration, or becomes the return value of the iterator after the last iteration.

          data = [2, 5, 3, 4]
          sum = data.inject {|sum, x| sum + x } # => 14 (2+5+3+4)
          floatprod = data.inject(1.0) {|p,x| p*x } # => 120.0 (1.0*2*5*3*4)

          max = data.inject {|m,x| m>x ? m : x } # => 5 (largest element)

What is the difference between Ruby 1.8.7 and 1.9.2?

What is the difference between Ruby 1.8.7 and 1.9.2?

   a).Pseudo-Keyword Hash Syntax
       Ruby 1.9 adds a cool feature that lets you write things like:
         foo(a: 1, b: 2)
         But on Ruby 1.8, we’re stuck using the old key => value syntax:
         foo(:a => 1, :b => 2)
   b).Multisplat Arguments
            Ruby 1.9.1 offers a downright insane amount of ways to process arguments to methods.
        def add(a,b,c,d,e)
           a + b + c + d + e
         end
    
       add(*[1,2], 3, *[4,5]) #=> 15
      The closest thing we can get to this on Ruby 1.8 would be something like  this:
       add(*[[1,2], 3, [4,5]].flatten) #=> 15

c).  Block-Local Variables
On Ruby 1.9, block variables will shadow outer local variables, resulting in the following behavior:
>> a = 1
=> 1

>> (1..10).each { |a| a }
=> 1..10
>> a
=> 1
This is not the case on Ruby 1.8, where the variable will be modified even if not explicitly set:
>> a = 1
=> 1
>> (1..10).each { |a| a }
=> 1..10

>> a
=> 10
d). Block Arguments
In Ruby 1.9, blocks can accept block arguments, which is most commonly seen in define_method:
define_method(:answer) { |&b| b.call(42) }
However, this won’t work on Ruby 1.8 without some very ugly workarounds

e).New Proc Syntax

Both the stabby Proc and the .() call are new in 1.9, and aren’t parseable by the Ruby 1.8 interpreter. This means that calls like this need to go:
>> ->(a) { a*3 }.(4)
=> 12
Instead, use the trusty lambda keyword and Proc#call or Proc#[]:
>> lambda { |a| a*3 }[4]
=> 12

f).Using Enumerator

In Ruby 1.9, you can get back an Enumerator for pretty much every method that iterates over a collection:
>> [1,2,3,4].map.with_index { |e,i| e + i }
=> [1, 3, 5, 7]
In Ruby 1.8, Enumerator is part of the standard library instead of core, and isn’t quite as feature-packed. However, we can still accomplish the same goals by being a bit more verbose:
>> require "enumerator"
=> true

>> [1,2,3,4].enum_for(:each_with_index).map { |e,i| e + i }
=> [1, 3, 5, 7]
 g). String Iterators
In Ruby 1.8, Strings are Enumerable, whereas in Ruby 1.9, they are not. Ruby 1.9 provides String#lines, String#each_line, String#each_char, and String#each_byte, all of which are not present in Ruby 1.8.

 h). Character Operations
In Ruby 1.9, strings are generally character-aware, which means that you can index into them and get back a single character, regardless of encoding:
>> "Foo"[0]
=> "F"
This is not the case in Ruby 1.8.6, as you can see:
>> "Foo"[0]
=> 70

 i).Encoding Conversions
Ruby 1.9 has built-in support for transcoding between various character encodings, whereas Ruby 1.8 is more limited. However, both versions support Iconv. If you know exactly what formats you want to translate between, you can simply replace your string.encode("ISO-8859-1") calls with something like this:
Iconv.conv("ISO-8859-1", "UTF-8", string)
j).Introduction of Fibers

Fibers are light-weight threads with manual, cooperative scheduling, rather than the preemptive scheduling of Ruby 1.8's threads.A fiber gets interrupted only when it yields its execution. So a fiber is a sort of user-managed thread. Threads use pre-emptive scheduling, whereas fibers use cooperative scheduling.
  

What is the difference between Proc and Lambda?

What is the difference between Proc and Lambda?

      Blocks are syntactic structures in Ruby; they are not objects, and cannot be manipulated
as objects. It is possible, however, to create an object that represents a block. Depending
on how the object is created, it is called a proc  or a lambda .

       Procs have block-like behavior and lambdas have method-like behavior. Both, however, are instances of class Proc .

       Creating & invoking procs:
             p = Proc.new {|x,y| x+y }
             p.call(1,2)
       
       Creating & invoking Lamdas:
            succ = lambda {|x| x+1}  =>Ruby1.8
               succ = ->(x){x>0} =>Ruby1.9
                succ.call(1)

        In a lambda-created proc, the return statement returns only from the proc itself
        In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!


      Differences:
        
Procs
Lambda
 A proc is the object form of a block, and it behaves like a block.

 Calling a proc is like yielding to a block.

 A proc is like a block, so if you call a proc that executes a return  statement, it attempts
to return from the method that encloses the block that was converted to the proc.
For Example:

def test
puts "entering method"
p = Proc.new { puts "entering proc"; return }
p.call  # Invoking the proc makes method return
puts "exiting method"  # This line is never executed
end
test

 break to do the same thing like return in a proc.


  proc handles the arguments it receives  flexibly:discarding extras, silently adding nil  for omitted arguments.

   p = Proc.new {|x,y| print x,y }
   p.call(1,2)  # prints 1,2
   p.call(1)  # prints 1, nil
 A lambda has slightly
modified behavior and behaves more like a method than a block.
 whereas calling a lambda is like invoking a method.

 A return  statement in a lambda returns from the lambda itself, not from the method that surrounds the creation site of the lambda:
For Example:
def test
puts "entering method"
p = lambda { puts "entering lambda"; return }
p.call
 # Invoking lambda does not make the method #return
puts "exiting method" 
# This line *is* executed now
end
test

break to do the same thing like return in a lambda.

 Lambdas are not flexible in this way; like methods, they must be invoked with precisely
the number of arguments they are declared with:

         l = lambda {|x,y| print x,y }
         l.call(1,2) # This works
         l.call(1) # Wrong number of arguments

   next statement works the same in a block, proc, or lambda.
   redo also works the same in procs and lambdas.
   retry is never allowed in procs or lambdas: using it always results in a LocalJumpError.
   raise behaves the same in blocks, procs, and lambdas. Exceptions always propagate up the call stack

Wednesday, 14 August 2013

dynamic programing in rails controller

Here is the simple code snippet for dynamic programming in rails controllers.

  def method_missing(c)
    render_error(404)
  end


The above method will be invoked when there was method missing exception was raised and we are redirected the request to specific page like 404.

Thank You,
Uma Mahesh

git commands

Here are the list of useful git commands.

> git config -l

List all variables set in config file.

> git config --global user.name "uma mahesh"
> git config --global user.email "umamaheshvarma@gmail.com"



Thank You,
Uma Mahesh.
 

Saturday, 13 July 2013

postgresql console interface


Here is the command to connect to postgresql through console,

> sudo -u postgres psql

The above command will connect to psql.

>  sudo -u postgres psql
psql (9.1.9)
Type "help" for help.

postgres=# 


Now you can run all the sql queries through this interface.



Thank You,
Uma Mahesh.




 

Wednesday, 10 July 2013

Hi,

While working with rspec I had issue as shown below.

undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_5::Nested_1

I didn't change any code modifications in the spces and my spces started failing with the error shown above. I have searched for the solution and I didn't found any specific solution for that. At last I came to find the issue is due to change in the Rspec version in my gem file.

I reverted back to my old gem file and finally able to solve the issue.

Thank You,
Uma Mahesh.

Sunday, 16 June 2013

couldn't find file 'twitter/bootstrap'

Twitter Bootstrap in rails application not working in production while deployed to heroku.

When I check for logs in heroku, I am able to see the below error.

ActionView::Template::Error (couldn't find file 'twitter/bootstrap')

While doing some google I came to see that, I have included  'twitter-bootstrap-rails' gem in development env in my gem file. So it was unable to load in production.

I have made the 'twitter-bootstrap-rails' gem public and bundle install again. Now every thing works fine.

Thank You,
Uma Mahesh.

sqlite3 error while pusing code to heroku


Below is the issue while I am trying to push the code to heroku for the first time.

rails@rails:/media/AAFA1CCBFA1C95A3/ruby/rails_app/simple_form/sample1$ git push heroku master
Counting objects: 99, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (88/88), done.
Writing objects: 100% (99/99), 39.73 KiB, done.
Total 99 (delta 3), reused 0 (delta 0)

-----> Ruby/Rails app detected
-----> Installing dependencies using Bundler version 1.3.2
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin --deployment
       Fetching gem metadata from https://rubygems.org/.........
       Fetching gem metadata from https://rubygems.org/..
       Installing rake (10.0.4)
       Installing i18n (0.6.1)
       Installing multi_json (1.7.7)
       Installing activesupport (3.2.13)
       Installing builder (3.0.4)
       Installing activemodel (3.2.13)
       Installing erubis (2.7.0)
       Installing journey (1.0.4)
       Installing rack (1.4.5)
       Installing rack-cache (1.2)
       Installing rack-test (0.6.2)
       Installing hike (1.2.3)
       Installing tilt (1.4.1)
       Installing sprockets (2.2.2)
       Installing actionpack (3.2.13)
       Installing mime-types (1.23)
       Installing polyglot (0.3.3)
       Installing treetop (1.4.14)
       Installing mail (2.5.4)
       Installing actionmailer (3.2.13)
       Installing arel (3.0.2)
       Installing tzinfo (0.3.37)
       Installing activerecord (3.2.13)
       Installing activeresource (3.2.13)
       Installing rack-ssl (1.3.3)
       Installing json (1.8.0)
       Installing rdoc (3.12.2)
       Installing thor (0.18.1)
       Installing railties (3.2.13)
       Installing bootstrap-daterangepicker-rails (0.0.5)
       Installing coffee-script-source (1.6.2)
       Installing execjs (1.4.0)
       Installing coffee-script (2.2.0)
       Installing coffee-rails (3.2.2)
       Installing commonjs (0.2.6)
       Installing jquery-rails (3.0.1)
       Installing less (2.2.1)
       Installing less-rails (2.2.3)
       Installing libv8 (3.3.10.4)
       Using bundler (1.3.2)
       Installing rails (3.2.13)
       Installing sass (3.2.9)
       Installing sass-rails (3.2.6)
       Installing simple_form (2.1.0)
       Installing sqlite3 (1.3.7)
       Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
       /usr/local/bin/ruby extconf.rb
       checking for sqlite3.h... no
       sqlite3.h is missing. Try 'port install sqlite3 +universal'
       or 'yum install sqlite-devel' and check your shared library search path (the
       location where your sqlite3 shared library is located).
       *** extconf.rb failed ***
       Could not create Makefile due to some reason, probably lack of
       necessary libraries and/or headers.  Check the mkmf.log file for more
       details.  You may need configuration options.
       Provided configuration options:
       --with-opt-dir
       --without-opt-dir
       --with-opt-include
       --without-opt-include=${opt-dir}/include
       --with-opt-lib
       --without-opt-lib=${opt-dir}/lib
       --with-make-prog
       --without-make-prog
       --srcdir=.
       --curdir
       --ruby=/usr/local/bin/ruby
       --with-sqlite3-dir
       --without-sqlite3-dir
       --with-sqlite3-include
       --without-sqlite3-include=${sqlite3-dir}/include
       --with-sqlite3-lib
       --without-sqlite3-lib=${sqlite3-dir}/lib
       --enable-local
       --disable-local
       Gem files will remain installed in /tmp/build_27eau1y5d86jq/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.7 for inspection.
       Results logged to /tmp/build_27eau1y5d86jq/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.7/ext/sqlite3/gem_make.out
       An error occurred while installing sqlite3 (1.3.7), and Bundler cannot continue.
       Make sure that `gem install sqlite3 -v '1.3.7'` succeeds before bundling.
 !
 !     Failed to install gems via Bundler.
 !

 !     Push rejected, failed to compile Ruby/Rails app

To git@heroku.com:simple-form-app.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:simple-form-app.git'

 Solution: 

Add this to your Gemfile,
group :production do
  gem 'pg'
end
group :development, :test do
  gem 'sqlite3'
end
 
then do a bundle then repush to heroku. You cannot use sqlite3 on Heroku - which is the cause of the error.

Thank You,
Uma Mahesh.


Wednesday, 12 June 2013

helper method from rails console

Hi,

I would like to test the helper method from the rails console. Can any one suggest me how I can invoke a helper method from console?

Thank You,
Uma Mahesh.