Monday, April 27, 2009

Gets Days from the difference between two dates.

Example:
> a = "2009-04-01 18:33:05"
> b = Time.now
> c = b.to_date - a.to_date
O/P: Rational(4, 1)
> c.to_i
=> 4
OR
> c = (b.to_date - a.to_date).to_i
=> 4

Generate Unique id

class Unique
def self.generate_unique_id(len)
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
generate_unique_id = ""
1.upto(len) { |i| generate_unique_id << chars[rand(chars.size-1)] }
return generate_unique_id
end
end

Example:
irb> Unique.generate_unique_id(18)
=> "CCDCa6Fv1AKsIaYAAA"

Ruby Chop vs Chomp

When you receive user input from textareas or console input you may get some newline characters. One way to remove newline characters is the String#chop method, it will remove any trailing newline or carriage return characters “\r\n”. But it’s tricky. Because here it works like it’s suppose to.

full_name = "My Name is Ravikanth\r\n" 

full_name.chop! # => "My Name is
Ravikanth"

Now if you run chop and there are no newline characters.

puts full_name    #=> "My Name is Ravikanth"

full_name.chop! #=> "My Name is
Ravikant"

Disaster Strikes!

That’s why there is chomp.

puts full_name       #=> "My Name is Ravikanth\r\n"

full_name.chomp! #=> "My Name is
Ravikanth"
full_name.chomp! #=> "My Name is
Ravikanth"

So chomp is our recommended way of removing trailing newline characters.