Archive for the 'Codes' Category

First Steps through Ruby on Rails


Image Source:www.flickr.com

Classes, attributes, methods, and objects are the core of any Object-Oriented language. I am going to discuss how these classes, attributes, methods etc can be implemented in Ruby. There are two types of classes ‘close-ended’ and ‘open-ended’. If a class is close-ended, then new functionalities cannot be added to it without inheriting the class.
If a class is open-ended, then new functionalities can be added to it without inheriting it. Ruby is open-ended.
The class declared and defined just now is an empty class as it doesn’t contain any attributes or methods. You will notice that the procedure to define methods in ruby is very simple. def is the keyword used to define methods.
In ruby we don`t use brackets to define a set of code and we don`t use any semicolon at the end of the statements.

Controlling iTunes Using RubyOSA

Did you know that RubyOSA provides a bridge from Ruby to the Apple Event Manager? It allows Ruby programs to automate Mac OS X applications in the same way as AppleScript.

Here’s an example code in controlling iTunes:

require ‘rbosa’
itunes = OSA.app(‘iTunes’)

track = itunes.current_track
p track #
p track.name # “Over The Rainbow”
p track.artist # “Keith Jarrett”
p track.duration # 362.368988037109
p track.date_added.to_s # “2006-06-30″
p track.enabled? # true

# Play the selected track.
itunes.play

# Fade the volume.
100.times { |i| itunes.sound_volume = i; sleep 0.1 }

# Set iChat’s status message to the current track.
OSA.app(‘iChat’).status_message = “Playing: #{track.name}”

Come on and try this out! :)

Fun With Unicode

Here’s an interesting post from Oreillynet.com. Did you know you can do this with Ruby out of the box?

# A real lambda
λ { puts ‘Hello’ }.call => ‘Hello’

# Sigma – sum of all elements
∑(1,2,3) => 6

# Square root
√ 49 => 7.0

How difficult was this to implement? Keep reading!

# Be sure to run with the “-Ku” flag!
module Kernel
alias λ proc

def ∑(*args)
sum = 0
args.each{ |e| sum += e }
sum
end

def √(root)
Math.sqrt(root)
end
end

Pretty tricky, eh?

Just remember the “-Ku”. :)

How I love Ruby On Rails Programming!

Copyright ©Basic Ruby On Rails Programming.