Posts filed under 'coding'

Exception Handling in Ruby

>begin expression executes its body and returns the value of the last evaluated expression.
>Any error in begin part will be caught by rescue depending upon parameters
>ensure is the one which must be exectued irrespective of exception occured or not
>An error message caught by an exception can be accessed using $!

For Java Programmers [ begin => try ; rescue => catch; ensure => finally]

begin
 p "I am doing well"
 p "so well .. and well"
 a = 8/0
rescue
 p "Something went wrong => " + $!
ensure
 p "Oh Somehow I could finish my work"
end

O/P:

“I am doing well”
“so well .. and well”
“Something went wrong => divided by 0″
“Oh Somehow I could finish my work”

a = 8
b = 0
begin
 p "I am doing well"
 p "so well .. and well"
 if a==18
    p "I am happy with a as 8"
 elsif b == 0
    p "Lets say I dont want this"
    raise Exception
 else
    raise
 end

rescue
    p "Exception 1 caught here " + $!
rescue Exception
    p "Exception 2 caught here " +$!
ensure
 p "Oh Somehow I could finish my work"
end

O/P for [[ a = 8 and b = 0 ]]
“I am doing well”
“so well .. and well”
“Lets say I dont want this”
“Exception 2 caught here Exception”
“Oh Somehow I could finish my work”

O/P for [[ a = 8 and b = 1 ]]
“I am doing well”
“so well .. and well”
“Exception 1 caught here “
“Oh Somehow I could finish my work”

Add comment April 18, 2008

RubyGems

A gem is a packaged Ruby application or library. It has a name and a version and have a specific task. Based on your requirement you may embed them into your application codes.

For eg.
activerecord 0.8.4
BlueCloth 0.0.4
captcha 1.1.2
cardinal 0.0.4
progressbar 0.0.3
rake 0.4.0

Gems are managed on your computer using the gem command. You can install, remove, and query gem packages using the gem command.

Installing RubyGems:
RubyGems is the name of the project that developed the gem packaging system and the gem command. You can get RubyGems from the RubyForge repository http://rubyforge.org/frs/?group_id=126
then type
ruby setup.rb
It installs the required library files and the gem command. This command gives us the power to do many things.

In a shortcut version at CLI we may use
q for query
r for remote
l for local
n for name
spec for specification

Listing remotely installable gems
gem query –remote

Searching remotely installable gems
gem query –remote –name-matches doom
# shortcut: gem q -R -n doom

Installing a remote gem
gem install –remote progressbar
or
gem ins -r progressbar-0.0.3
or
gem ins -r progressbar –version ‘> 0.0.1′
RubyGems allows you to have multiple versions of a library installed and choose in your code which version you wish to use.

Looking at an installed gem
gem specification progressbar

Listing all installed gems
gem query –local

remote or local
If you don’t specify either of these, then gem will (usually) try ’’both’’ a local and remote operation. For example:
gem ins rake # Attempt local installation; go remote if necessary
gem list -b ^C # List all local AND remote gems beginning with “C”

Coding With RubyGems
require ‘rubygems’
require ‘progressbar’
and then subsequently
bar = ProgressBar.new(“Example progress”, 50)

The first line of the program requires the progressbar library file. RubyGems will look for the progressbar.rb file in the standard library locations. If not found, it will look through its gem repository for a gem that contains progressbar.rb. If a gem is used, RubyGems attempts to use the latest installed version by default.

Specifying Versions
gem install –remote rake –version “0.4.14″

Updating RubyGems
gem update –system
or
gem install rubygems-update
update_rubygems

Uninstalling a gem
gem uninstall progressbar

Info extracted from : http://rubyforge.org/

Add comment April 12, 2008

and vs && in ruby

p true and false
p true && false
# true, false

p false and true
p false && true
# false, false

p true or false
p false or true
# true, false

p true || false
p false || true
# true, true

What happened???? You mean to say AND and && is different. In the same way OR and || behave in a distinct manner. No.

Still I don’t have a proper answer, except telling that here jack is with “p” or “puts” which always evaluates the very first parameter in case of “and” or “or”. When we use symbolic “&&” / “||” may be some precedence rule, which forces print statement to evaluate by having both operands left and right as well. means

p true && false ==> becomes ===> p (ture && false) , whereas

p true and false ==> becomes ===> p true //takes only one argument.

Please if someone has got a proper answer let me know.

2 comments April 12, 2008

do while in ruby

How to achieve the do ..while loop in Ruby?
Yes this can be, just bit tricky.
Just consider one of the syntax of while loop in ruby

<expression> while <expression>

This repeats evaluation of left hand side expression, while right hand side is true.

x = 5
begin
  print x
  print " "
  x += 1
end while(x<10)

o/p
5 6 7 8 9

Add comment April 7, 2008

Class is an object

Are you really into a position to justify these outputs??
If so, means your OOP concepts in RUBY is clear else ……..

class Acer
 // Jacobian Code
end

Acer.class      > Class
Acer.superclass >  Object
Class.superclass> Module

2.class        > Fixnum
2.988888.class > Float
-2.class       > Fixnum
"2".class      > String
0x22.class     > Fixnum

Class.class    > Class
nil.class      > NilClass
self.class     > Object
Object.class   > Class
Object.type    > Class
Time.class     > Class
Time.now.class > Time

Add comment April 6, 2008

blank,empty and nil in Ruby

Object.blank?

Returns true if:
> it’s an empty array
> it’s an empty string
> !self evaluates to true

[].blank? #=> true
[1].blank? #=> false
[nil].blank? #=> false
nil.blank? #=> true
true.blank? #=> false
false.blank? #=> true
"".blank? #=> true
" ".blank? #=> true
" i ".blank? #=> false

String.empty?

"hello".empty? #=> false
"".empty? #=> true

Array.empty?
[].empty? #=> true

Hash.empty?
{}.empty? #=> true

NilClass.nil?
nil.nil? => true

Object.nil?
nil.nil? => true
.nil? => false
nil.inspect ? "nil"

Add comment April 5, 2008

Ruby nil is kicking you

Ruby is said to be a genuine Object Oriented Language. Everything is an object; even a class and moreover even nil.
Basically nil tells you about an absence of a value (or an otherwise meaningless value). n/a is a good candidate for a nil value.
The nil value is distinct from all other values. However, when we force Ruby to evaluate nil as a Boolean, it evaluates to false.

“Prayas” if nil
=> nil

“Prayas” if !nil
=> Prayas

The only values that evaluate to false Booleans are nil and false. Everything other than nil or false evaluates to true when forced into a Boolean. Zero is also evaluated as true(not as false) great!!!!

“Prayas” if false
=> nil

“Prayas” if nil
=> nil

“Prayas” if -5
=> Prayas

“Prayas” if 0
=> Prayas

nil.methods # gives you all methos

But here I am interested for methods which starts with to_. Lets gather those.

nil.methods.grep(/^to_.$/)
[”to_f”, “to_a”, “to_s”, “to_i”]

And what are they giving to me:

nil.methods.grep(/^to_.$/).each do |method_name|
puts “nil.#{method_name} :: #{nil.send(method_name).inspect}”
end

o/p
nil.to_f :: 0.0
nil.to_a :: []
nil.to_s :: “”
nil.to_i :: 0

Convert a nil value to 0 in order to avoid crash.
a = 25
b = nil
c = nil
d = “mystring”
p a||=0 # returns 25 as a is not nil
p b||=0 # returns 0 as b is nil
p c.to_i # returns 0 as nil is casted to int ,i.e other way
p d||=0 # returns “mystring” as d is not nil

so we got TWO ways to convert nil value to 0
1. using myvar ||= 0
2. using myvar.to_i OR (to_f, to_a, to_s, to_i )

How to handle when you get a crash because of nil?

def mymethod(para1)
p para1.to_s.upcase
#p para1.upcase
end

mymethod(”Prayas”)
mymethod(”Attempting”)
mymethod(nil)

o/p:
PRAYAS
ATTEMPTING
“”
The .to_s allows nil to be passed in without failure.
Without the .to_s you would receive this:(i.e if you use para1.upcase)
undefined method `upcase’ for nil:NilClass (NoMethodError)

In your views you may use something like to avoid crash
<%= @instance_name.variable_name rescue nil %>

Add comment March 22, 2008

Variable vs Objects

person = “Tim”
p person.object_id
p person.class

p person
#~ 22901710
#~ String

#~ “Tim”

- Ruby creates a new String object with the value “Tim”
- A reference to this object is placed in the local variable person.
- The o/p revels this variable(person) has indeed taken on the personality of a string, with an object id, a type, and a value.

So, is a variable an object?
NO.
- A variable is simply a reference to an object.
- Objects float around in a big pool somewhere (the heap, most of the time) and are pointed to by variables.

person1 = “Tim”
person2 = person1
person2[0] = “J”

p person1.object_id
p person2.object_id
p person1

p person2

#22899620
#22899620
#”Jim”
#”Jim”

variables hold references to objects, not the objects themselves.
- person2 = person1 :: doesn’t create any new objects;
- it simply copies person1’s object reference to person2, so that both
person1 and person2 refer to the same object.

So = symbol here works as an aliasing object >> Gives you multiple variables
And all these variables reference to the same object.

Then how can we create a duplicate object instead a reference variable ?

Using dup method:
person1 = “Tim”
person2 = person1.dup
person1[0] = “J”
p person1.object_id
p person2.object_id
p person1
p person2

#~ 22901200
#~ 22901190
#~ “Jim”
#~ “Tim”

variables vs objects

But what if you want to prevent from any modifications to the object?
person1 = “Tim”
person2 = person1
person1.freeze # prevent modifications to the object
person2[0] = “J” # can’t modify frozen string (TypeError)

Add comment March 22, 2008

find(ActiveRecord::Base)

# returns the object for very first row or dierctly put the first row ID like 156789
find_first_as_object = Rating.find(:first)
#p find_first_as_object.ratee_identity_id #1287065605

find_first_as_object_using_idnum = Rating.find(1) # search for id =1

# returns as an array of object(one element array)
find_first_as_array = Rating.find([569384240])
# p find_first_as_array[0].ratee_identity_id #1287065605

find_first_with_condition = Rating.find(:first, :conditions => [”rating = 4?])
==================================

find_objects_with_selected_attributes = Rating.find(:all,:select => ‘rating as RR’)

my_distinct = Rating.find(:all, :select =>”distinct rating” )

find_first_with_condition_plus_order = Rating.find(:first,
:conditions => [”rating = 4?], :o rder => “ratingdate DESC”)
===================================

find_all = Rating.find(:all) # returns an array of objects

find_all_by_limit = Rating.find(:all, :conditions => [”rating >= 3 “],:limit => 10)

find_all_by_group = Rating.find(:all,
:conditions => [”rating >= 3 “],
:group => “rating”)
===================================

# find_by_sql returns an ARRAY of objects
find_sql = Rating.find_by_sql(”select rating as goodRating from ratings where rating >=3?)

find_sql_using_var = Rating.find_by_sql(”select * from ratings where id = ?”, ratee_identity_id)
===================================

find_first_by_rating = Rating.find_by_rating(”3?)
# Rating.find(:first, conditions => “rating = 3”)

find_all_by_rating = Rating.find_all_by_rating(”3?)
# Rating.find(:all, conditions => “rating = 3”)

Add comment March 22, 2008

@content_for_layout

If you create a template file in the app/views/layouts with the same name as a controller, all views used by that controller will use that layout by default.controller/store_controller.rb ::::: consists of method1 & method2def method1
@first_name = “Rajesh”
end

def method2
@last_name = “Kumar”
end

views/store :::::: consists two html method1.rhtml & method2.rhtml

method1.rhtml
<h2>My first name is :: <%= @first_name %> </h2>

method2.rhtml
<h2>My last name is :: <%= @last_name %> </h2>

views/layouts/store.rhtml ::::: same as controller’s name
<html>
<body>
<h4>This is the main template </h4>
<i> Rails automatically sets the variable @content_for_layout to the page specific content- the stuff generated by the view invoked.</i>
<div>
<%= @content_for_layout %>
</div>
</body>
</html>

http:// ………/store/method1
This is the main template
Rails automatically sets the variable @content_for_layout to the page specific content- the stuff generated by the view invoked.
My first name is :: Rajesh

http:// ………/store/method2
This is the main template
Rails automatically sets the variable @content_for_layout to the page specific content- the stuff generated by the view invoked.
My last name is :: Kumar

Add comment March 22, 2008

Previous Posts


@@name=PRAYAS

gap_resize.jpg

Time.now()

January 2010
M T W T F S S
« May    
 123
45678910
11121314151617
18192021222324
25262728293031

order[:category]

posts[:recent]

episodes[:recycled]

links[:favourite]

vote_for_web2.0

Step down at my blog with your ideas,comments,suggestions on Ruby,RoR,Ajax or Web2.0 Technology. You may reach me at rajesh4it@gmail.com.

@visitors.count(Feb’08)

find_all(:categories)

Around me bollywood coding news@RoR Rails RoR Ruby Tools&Tips Web2.0 talks

Vote for RoR

Blog Stats