Showing posts with label Ruby methods. Show all posts
Showing posts with label Ruby methods. Show all posts

Sunday, April 5, 2009

Nice output for Ruby objects

Ruby has a wide range of methods to format the output of an object.

Like

1) Inspect
2) y or to_yaml
3) PrettyPrint

y is actually used as a shorthand for to_yaml

example
 
a={'1'=>'one','2'=>'two','3'=>'three','4'=>'four'}

y a

puts a.to_yaml

generates the same output.

Below are the ouputs using different output methods

> Using normal puts
 
usage: puts a

output:

1one2two3three4four

Using y or to_yaml

usage: y a or puts a.to_yaml

output:

"1": one
"2": two
"3": three
"4": four

> Using PrettyPrint

usage: Please do a require 'pp' in your script file,
 
pp a

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

> Using inspect
 
usage: puts a.inspect

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

Thursday, April 2, 2009

Ruby - DUP vs CLONE

Both DUP & CLONE can be used to create shallow copy of an object. Both copies the instance variables of obj. But we need to be selective in their usage.

Few difference between these are

1) CLONE copies both FROZEN and TAINTED state of an object, where as DUP only copies TAINTED state of an object.

2) With CLONE you can copy any singleton methods of an object but DUP does not support this.

CLONE is used to duplicate an object, including its internal state, DUP typically uses the class of the descendent object to create the new instance.

I had some bitter experience while using DUP for duplicating an ActiveRecord row, this ended up in losing the original one the same worked fine with CLONE.


A good article on Objects states can be found here


Frozen state:

The object can not be modified any more.

Example
 
a = [ "a", "b", "c" ]
a.freeze
a << "z"

Will return

`<<': can't modify frozen array

Wednesday, March 25, 2009

Binary conversion in Ruby

We hardly stretch ourselves to limit unless situation demands to do so.

My requirement - convert a decimal to binary conversion

My first impression - there would be a to_b default method available in ruby which I can use straight away. But it was not so.

But as always it is quite simple to do it in ruby,

number.to_s(2)

gives the binary equivalent of the number

try this from ur IRB

3.to_s(2)

similarly for any base conversion just pass the base value to to_s

Example

3.to_s(10) for base 10 conversion.

Monday, September 22, 2008

Three ways to invoke a method in ruby

1. object = Object.new
puts object.object_id
#=> 282660

2. puts object.send(:object_id)
#=> 282660

3. puts object.method(:object_id).call
#=> 282660

why in ruby nil.object_id is equal to 4 ?

A very good explanation found at http://www.joesniff.co.uk/ruby/rubyrails-interview-questions.html

The object_id method returns the identity of an object. Every object must have a unique id. Hence if two objects have the same object_id, they are the same object.

Ruby’s booleans and nil are objects, so they deserve to be treated like real objects just like the rest. So they too should have an object_id.

When allocating object ids we are restricted with what ids we can use as Fixnum uses the odd object_ids (well all those needed to reach the maximum Fixnum). It takes the odd ids as the least significant bit is always set to 1 to flag this as a Fixnum.

So starting at the sensible point of 0 this leaves us with the following order:

0 => False
1 => 0 (Fixnum)
2 => True
3 => 1 (Fixnum)
4 => Nil
5 => 2 (Fixnum)
6 => Undefined

Monday, April 14, 2008

Increment/decrement operator's in Ruby

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Methods in a class

To find the pre defined methods defined for a class type

ri classname
in your command prompt

Example --- ri File ; ri String

Friday, April 11, 2008

Use params, not @params

Frequently people in the #rubyonrails channel use @params in their code. For a while now @params has been deprecated in favor of simply params. For those who just skim these blog posts:
Use params, not @params

Why? When you use the params method, it allows for the implementation details of the parameter hash to be changed without breaking existing code. If the implementation of params changed you wouldn’t have to change your code at all because the single point of access for the parameters would just remain the params method. So, the details of what is happening behind the scenes don’t matter. If, though, you use the @params instance variable directly, you’ve broken encapsulation and consequently the ability for the implementation to be easily modified. Methods can be refactored, but instance variables can’t. Today the params method just wraps the @params instance variable, so still using @params works, but that’s not guaranteed to always remain the case.

Same goes for request, response, session, headers, template, cookies and flash.

Basically, a good rule of thumb here is don’t use an instance variable in your controller or view unless you created that instance variable.

Even the old @content_for_layout in the layout is deprecated in favor of just using yield in its place. Also content_for('some_fragment') is now accessed with yield :some_fragment rather than @content_for_some_fragment.