Friday, May 25, 2012

Ruby 1.9.3 - defined?

defined?
It's a ruby method for checking passed expression defined or not

Some examples

1.9.3p0 :025 > message = "hello" => "hello" 1.9.3p0 :031 > defined? message => "local-variable" 1.9.3p0 :032 > if defined? message 1.9.3p0 :033?> puts "message defined" 1.9.3p0 :034?> end message defined
1.9.3p0 :050 > defined? $_ => "global-variable"

1.9.3p0 :052 > defined? lastname => nil

1.9.3p0 :053 > books = [] => [] 1.9.3p0 :054 > defined? books => "local-variable"

1.9.3p0 :055 > name = "" => "" 1.9.3p0 :056 > defined? name => "local-variable" 1.9.3p0 :057 > author = "Steve" => "Steve" 1.9.3p0 :058 > defined? author => "local-variable" 1.9.3p0 :059 > object = String.new => "" 1.9.3p0 :060 > defined? object => "local-variable"

I hope you understand defined? method from these examples.

Tuesday, May 22, 2012

Procs in rails 3

Proc is an object of code blocks that are assigned into variable.Proc and Blocks are same, but the primary difference is performance.

def say_message_with_name(message) Proc.new do |name| message + " " +name end end
message1 = say_message_with_name("Good morning") message1.call("Tom")
In this example, simply show message with name. Proc is created when constructor is called and given a block as a parameter

The code in the block is treated as Proc instance and can be called any time.You can call Proc code block anytime using "call" method

Output of above example

1.9.3p0 :011 > def say_message_with_name(message) 1.9.3p0 :012?> Proc.new do 1.9.3p0 :013 > |name| message + " " +name 1.9.3p0 :014?> end 1.9.3p0 :015?> end => nil
1.9.3p0 :016 > message1 = say_message_with_name("Good morning") => #<Proc:0x8e8382c@(irb):12> 1.9.3p0 :017 > message1.call("Tom") => "Good morning Tom"

Purpose of Proc

If you want to create a block of code and pass it around on you're application or generate new blocks from existing block.

Blocks in rails 3

Blocks are generally simple code wrapped in a do/end construct.

Example

books = %w{book1 book2 book3 book4}
books.each do |name| print "Book name :: #{name}\n" end

In this example code between do and end is Blocks. what it does is that iterates an array using the each method and passes in each element(i.e name) to the code block

GitHub for Windows

GitHub announced GitHub for Windows

http://windows.github.com/

Read this article for more information
https://github.com/blog/1127-github-for-windows

Monday, May 21, 2012

Ruby method calling

Different way of Ruby method calling

puts "Hello world"
puts ("Hello world")
puts
puts()

Above type applies only ruby puts method. it may vary for other methods based on definition