@akdom
As Mike said, in ruby everything is an object, unlike Python where the primitives are, well, primitive. Another really elegant aspect of Ruby is anonymous code blocks. They're used all over the place, especially to replace loops that you see in other languages.
For example, if you want to repeat something 15 times, you can write:
15.times do
# do something here
end
Notice that you can actually read this like it's english.
Or if you want to loop over an array, you can do:
%w{one two three}.each do |word|
# this code is repeated with word = "one", then "two", then "three"
end
Naturally it supports map and reduce (called inject) as well:
# sum the absolute values of every number in the array
nums.map { |x| x.abs }.inject(0) { |acc,i| acc + i }
If you use Ruby on Rails, or Ruby 1.9, this can be simplified even further:
nums.map(&:abs).inject(0, &:+)
In this case the &:abs
sequence is the same as :abs.to_proc
which returns an anonymous code block that calls the abs
function on its first argument. And &:+
returns an anonymous code block that calls +
on its first argument, passing in the second argument to the +
method.
Another common thing to do in Ruby is to write a DSL. One of the more popular ones is used by Rake, a make replacement for Ruby. A simple Rakefile might look like this:
desc "Build and run"
task :run => [:build, :launch]
desc "Build the project"
task :build do
sh "xcodebuild -configuration Release build OBJROOT=build/ SYMROOT=build/"
end
desc "Clean the project"
task :clean do
sh "xcodebuild clean OBJROOT=build/ SYMROOT=build/"
end
task :launch do
sh "build/MyProject.app/Contents/MacOS/MyProject"
end