Sunday, July 12, 2009

Ruby Notes

Here are my quick notes about some Ruby tips for beginners.

Installation and Gems



Gems is Ruby's CPAN ;) If you are installing on Windows make sure to include gems in the installation. By default its turned off for 'Ruby 1.8.6 One-Click Installer'. You can get it from http://www.ruby-lang.org/en/downloads/. You can use the 'irb' tool to use Ruby on the fly (aka REPL)



Rspec


Rspec is Ruby's testing framework. You can install it using 'gem install rspec' on the command line. http://rspec.info/ is the main documentation site for it. Just type 'spec -h' on the command line for more information about how to run it. Cucumber is another functional testing framework which is becoming popular - apparently, I don't even know the official URL to it, so just search for it!



Some Language Syntax



Variable naming conventions:

local @instance @@class $global CONSTANT Constant



Class and method declarations using optionally accessors:


class MyClass

attr_accessor :name
attr_reader :someother1
attr_writer :someother2

def name
return @name
end

def name=(name)
@name = name
end

end

Arrays and hashes:

{:a => 1}.each { |k, v|
puts k + ": " +v
}

[1,2,3].each do |i|
puts i
end

The colon notation creates unique identifiers eg.
:name



Mix-ins are another way of extending your classes. They are defined and used as


Module A
end

class X
include A
end



Yield and Blocks



Block are anonymous functions
You can use yield keyword to execute the block which is passed to a function.


def some_func
yield
end

some_func do
puts "yield is running me!"
end

You can use 'block_given?' special variable to check whether a block passed to a function or not.



Useful Ruby for Ruby



You can use the ruby2ruby module to interpret ruby code within a Ruby script.

gem install ruby2ruby
Another useful gem is ruby_degug (
gem install ruby_debug
)