Archive for 'Ruby'

Ruby File Path Separators

File path separators on Unix systems and Windows are different. On Unix, a forward slash / is used and on Windows a backslash \ is used. However, when writing Ruby code you don’t need to worry about this; Just use the forward slash / character and it will be cross-platform for you. An even better […]

Instance and Class Variable Accessor Methods

When you define classes in Ruby, you must specify what kind of access you want to give Instance and Class attributes/variables which are defined in that class. The way you do it is that you write reader and writer methods. You can write these methods out explicitly or use the shorthand attribute (attr_) methods like […]

Ruby Iterators

Here are some Ruby Iterators and description of how they can be used: times Iterate through the block 3 times, n starts at 0 and ends at 2 and is incremented by 1 each time. n is the block variable. upto Iterate through the block 3 times, starting at 1 and ending at 3, each […]

Ruby Require VS Load VS Include VS Extend

Here are the differences between Require, Load, Include and Extend methods: Include When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your […]

How to Write a Singleton Class in Ruby

A Singleton is a Design Pattern which is used to prevent a class from being instantiated more than once. So there can only be one object of that particular type of class. Writing a Singleton Class in Ruby is very easy and much more straight forward than doing it in Java, for example. It uses […]

nokogiri – Ruby XML Parser Installation Headaches

Installation sudo gem install nokogiri Do you have an old version of libxml2? create a file called test.rb with the following contents: require ‘rubygems’ require ‘nokogiri’ Execute it: ruby test.rb If you see the following: “HI. You’re using libxml2 version 2.6.16 which is over 4 years old and has plenty of bugs. We suggest that […]

Ruby Time formatting and datetime SQL Column

If you’d like to format Time in Ruby, keep in mind that datetime SQL Columns translate to Time objects. So you can use the strftime method of the Time class to format the date/time. For example, assume scheduled_time is a field in your database and it has a sql data type of ‘datetime’. In your […]

Ruby Blocks

What is a block? A block allows you to pass another function to a function (method) as an argument. A block can only be passed in as a method argument. A block is a nameless function. Lambda method The lambda method is defined in Kernel module and returns a Proc object. A block can be […]