January 2012
8 posts
2 tags
Using Enumerable::inject to modify a hash
Ever wanted to modify the keys and values of a Hash? Enumerable::inject has you covered.
Try this snippet from Stack Overflow:
my_hash = { a: 'foo', b: 'bar' }
# => {:a=>"foo", :b=>"bar"}
a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k.upcase] = v.upcase; h }
# => {:A=>"FOO", :B=>"BAR"}
2 tags
Once set, variables are always defined
When you set a variable in a section of code that is never executed, the variable will still be defined.
if false
a = 'whatever'
end
puts a
# => "nil"
# Does NOT raise 'NameError: undefined local variable or method `a' for main:Object'
This post was submitted by Olivier El Mekki.
2 tags
String#gsub with a block generates the...
String#gsub is a common method for finding and replacing all occurrences of a text in a string. It is often used, like this:
"Where is the needle in the haystack?".gsub('needle', 'NEEDLE')
# => "Where is the NEEDLE in the haystack?"
But gsub can also use regular expressions, like this:
"Where is the needle in the haystack?".gsub(/n\w{5,}/, '*')
# => "Where is the * in the...
1 tag
The =~ and !~ operators
The operator =~ matches a String against a regular expression pattern. It returns the position/index where the String was matched - or nil if no match was found:
/Quick/ =~ "Ruby Quicktips"
# => 5
# Order does not matter
"Ruby Quicktips" =~ /Quick/
# => 5
"Ruby Quicktips" =~ /foo/
# => nil
Because it returns nil when no match is found, you can for example use this as a condition...
1 tag
Enumerable#reverse_each
reverse_each is like Array#each or Hash#each - in reverse:
a = [1,2,3]
a.each { |v| puts v }
# 1
# 2
# 3
a.reverse_each { |v| puts v }
# 3
# 2
# 1
1 tag
Rails' Hash#reverse_merge
Ruby’s Hash#merge combines two Hashes, where the second Hash replaces values with the same key of the calling Hash.
Rails adds the method Hash#reverse_merge which keeps the contents of the caller. This gives you - for example - an elegant way to specify default values for an optional argument Hash:
def my_method(options = {})
options = options.reverse_merge(:option1 => "foo",...
2 tags
ri: Ruby Interactive documentation
ri stands for “Ruby Interactive” and provides documentation on Ruby itself and most gems. You access it from the command line.
Here are some samples:
ri Array
ri select
ri Hash#select
ri Array#select
ri ActiveRecord::Base
ri -l #lists all classes with ri docs
(If you want to access the RDoc documentation, there’s a tip for that, too: Easy Access to the API Docs for Gems.)
3 tags
Prevent rdoc and ri installation when installing a...
When installing a gem the process that often takes the longest is generating the ri and RDoc documentation.
If you want to prevent this from happening every time a gem gets installed (either manually or through Bundler), create (or open) a .gemrc file in ~/.gemrc or /etc/gemrc and add the following two lines:
install: --no-ri --no-rdoc
update: --no-ri --no-rdoc
(If you want to overwrite...
September 2011
6 posts
1 tag
Inline While and Until
Similar to if and unless, while and until can be used inline, too:
round = 0
puts round += 1 until round > 9
round = 0
puts round += 1 while round < 10
1 tag
Associations with Conditions
You can specify ActiveRecord Associations with a condition on them:
class Post
has_many :comments
has_many :published_comments,
:class_name => "Comment",
:conditions => { :published => true }
end
One possible use-case is that you can use these associations to eager load only a subset of the associated records:
post = Post.find(1, :include =>...
1 tag
Ways to define class methods
There are different ways to create class methods in Ruby. These three are probably the most common ones. They all do the same.
class Blog
def self.foo
puts 'I am a class method'
end
def Blog.bar
puts 'I am a class method, too'
end
class << self
def foobar
puts 'I am another class method'
end
end
end
There are even more ways to define class...
1 tag
Execute Ruby Code from the Command Line
This is the quickest way to execute ruby code:
ruby -e "puts 'Hello World'"
1 tag
Check the Syntax of a Ruby Script
This will check the syntax without executing the program:
ruby -c filename.rb
1 tag
Sandbox your console hacking
When you start you Rails console, you can add the --sandbox parameter and all you modifications to the database will be rolled back again when you exit the console.
rails console --sandbox # Rails 3
script/console --sandbox # Rails 2
August 2011
5 posts
1 tag
Convert Object to Array
Have you ever been in a situation where you needed a method that does all of the following?
Convert nil to an empty Array, and
convert a non-Array variable n to [n], and
leave the Array variable as is.
The way to achieve this, is using the little known method Array():
Array(nil) # => []
Array([]) # => []
Array(1) # => [1]
Array([2]) # => [2]
1 tag
Dynamic Scopes
Rails 2.3 introduced dynamic named scopes. Dynamic scopes are created for each attribute in your model, prefixed by scoped_by_:
# A dynamic scope for a single attribute
Post.scoped_by_category('tech')
# => SELECT "posts".* FROM "posts" WHERE "posts"."category" = 'tech'
# One for multiple attributes, concatenated by '_and_'
Post.scoped_by_category_and_author_id('tech', 1)
# => SELECT...
2 tags
Step through your Cucumber features one step at a...
If you want to step through your cucumber scenarios simulating an interactive debugger, add this hook:
AfterStep('@pause') do
print "Press Return to continue..."
STDIN.getc
end
Then tag any feature with “@pause” and you’re all set.
2 tags
Rails 3, Bundler and forking gems
Did you know you can specify a Github repo or custom path to a gem in your Gemfile? Either stay up to date with bleeding edge changes or fork your own version. In your Gemfile:
# Referencing Github
gem 'sg-ruby', :git => 'git://github.com/simplegeo/simplegeo-ruby.git'
# Referencing local copy
gem 'sg-ruby', :path => "/Users/user/gems/simplegeo-ruby"
2 tags
Directly access an object if it's present
If you want to access an object only if it’s present, you can use Rails’ Object#presence.
The API docs on presence have a good explanation:
This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:
state = params[:state] if params[:state].present?
country =...
June 2011
4 posts
1 tag
It's now rubyquicktips.com
This blog now has its own domain.
http://rubyquicktips.tumblr.com is now http://rubyquicktips.com.
1 tag
Check if your associations have been eager loaded
If you want to check if associations of an object have been eager loaded, use the loaded? method:
@blogpost = Post.includes(:comments).find(1)
@blogpost.comments.loaded?
=> true
@blogpost = Post.find(1)
@blogpost.comments.loaded?
=> false
This might for example be useful to test eager loading in your tests.
1 tag
Eager loading
When you load records from the database and also want to access the associated objects for each of these records, it’s a good idea to make use of eager loading. Eager loading reduces the amount of queries made to the database and therefor increases performance.
A good example is an index view where you want to display an overview of information on a particular group of objects, including...
1 tag
Spread command chains across multiple lines
Ruby’s syntax allows you to spread command chains across multiple lines:
puts "You can do a lot with this in one line".reverse.sub('eno', 'elpitlum').sub(' htiw tol a', '').reverse.<< 's, too!'
…can also be written like this:
puts "You can do a lot with this in one line".
reverse.
sub('eno', 'elpitlum').
sub(' htiw tol a', '').
reverse.
<< 's, too!'
In Ruby...
May 2011
4 posts
1 tag
Execute shell commands
There are a number of different ways to run shell commands from Ruby.
The exec command
Kernel#exec replaces the current process and runs the command:
exec('ls ~')
# Nothing after this command is executed
This might be a bit impractical, so have a look at the other options.
Backticks or %x shortcut
Place your command inside backticks (`) or execute it within %x() and it will return the...
2 tags
Hash: new create syntax
Additional to the syntax for creating hashes we all know:
hash = { :first => "ruby", :second => "rails" }
# => {:first=>"ruby", :second=>"rails"}
hash[:first] # => "ruby"
…Ruby > 1.9.1 adds support for another syntax:
hash = { first: "ruby", second: "rails" }
# => {:first=>"ruby", :second=>"rails"}
# you still have to access a value via a...
2 tags
Merge or reverse_merge a Hash
Ruby’s Hash#merge lets you merge two Hashes. Duplicate entries in the merged Hash taking precedence over then ones in the calling Hash:
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
h1 #=> {"a"=>100, "b"=>200}
Rails’ Hash#reverse_merge takes the opposite approach when...
2 tags
Parse a string into a DateTime object. Controlled.
Just as you can format a string from a Time object with Time#strftime, you can also parse a string in a defined format into a DateTime or Date object, using DateTime#strptime or Date#strptime respectively (Date#strptime only creates a date without the time, though).
require 'date'
parsed_time = DateTime.strptime('03/05/2010 14:25:00', '%d/%m/%Y %H:%M:%S')
parsed_time.to_s
=>...
April 2011
3 posts
2 tags
Using "try" with a hash to check existence of a...
The try method is awesome. Check the documentation.
It is usually used to call a method on an object if it exists, or return nil if it doesn’t.
But sometimes, it is not used with hashes, but this also works perfectly:
params[:search] ? params[:search][:name] : nil
# Can also be written as...
params[:search].try(:[],:name)
Clean!
This tip was submitted by Miguel Camba.
2 tags
Format a string from a Time object
If you only want to print the first day of the current month you can use the string formating method on a Time object:
> Time.now.strftime("%Y-%m-1")
"2011-04-1"
The method can be used to print date in almost any format:
> Time.now.strftime("%A %B %d or %a %e/%m")
=> "Monday April 11 or Mon 11/04"
Check out Time#strftime for a list of directives. Time is part of the core, so...
2 tags
Heredoc and Indent
Heredocs come in handy when you have to deal with larger multi-line strings in the source code itself. However, it usually breaks the indents:
class Poem
def initialize
@text = <<END
"Faith" is a fine invention
When Gentlemen can see
But Microscopes are prudent
In an Emergency.
(Emily Dickinson 1830-1886)
END
end
def recite
puts @text
end
end
But it wouldn’t...
February 2011
4 posts
2 tags
Rails 3 Validation Shortcut
In Rails 2 the only way to add multiple validations to a field is through separate validate statements:
validates_presence_of :title
validates_length_of :title, :maximum => 30
Rails 3 simplifies this process by adding a method called validates which is a “shortcut to all default validators”. Using the validates method your code will look like this:
validates(:title,...
2 tags
How to define infinite numbers
You can define the “number” ‘infinity’ (or ‘-infinity’) in Ruby like this:
1.0/0
=> Infinity
-1.0/0
=> -Infinity
Infinity and -Infinity behave just like you expect them to: they are always bigger - or always smaller, respectively - than any number you compare it to.
The Xing Devblog had a great post recently about using Ruby’s infinity in Rails,...
2 tags
Grep an object's available methods
Because Object.methods returns an array, you can grep that just like in this tip about grepping anything from your enumerables.
For example, if you are looking for a particular method of an object, you can easily narrow down the results like this:
Object.methods.grep /inspect/
=> ["inspect", "pretty_inspect", "pretty_print_inspect"]
This tip was submitted Adam Rogers.
1 tag
How to check if objects or relations exist
Here’s an interesting fact when checking if objects or relations exist in a collection.
To check if there were any items present in a collection you can do something like this:
Object.relation.present?
This, however, is better:
Object.relation.any?
Turns out that - when you request associated objects for the first time - the any? method will perform a COUNT (*) SQL query where...
January 2011
6 posts
1 tag
Benchmark.ms: Rails you sneaky devil.
I am sure that we have all had to track how long some bit of code takes to process. For auditing purposes or whatever. The typically way we do this is to save the time just before the execution of our action, perform the action, and then get the time when the action completes. End time - Start time = Elapsed time. Hurrah! Look at us being geniuses….
And now for the “bring you back to earth...
1 tag
Random choice - eh, I mean sample - of an array's...
Need a randomly chosen element from an array? There’s a method for that! Array#choice (Ruby 1.8.7) or Array#sample (Ruby > 1.8.7):
[1,2,3,4,5,6,7,8,9].choice
=> 5
[1,2,3,4,5,6,7,8,9].sample
=> 8
[1,2,3,4,5,6,7,8,9].sample(3)
=> [3,8,9]
Thanks to everyone who mentioned these methods here and here.
1 tag
How to Call Private Methods On Objects
Calling private methods can for example be useful in unit testing to increase the code coverage. Object#send gives you access to all methods of a particular object (even protected and private ones).
obj.send(:method [, args...])
In case send method has been overwritten, you can also use its aliased version __send__.
1 tag
attr_accessor_with_default
Here’s a method I haven’t seen before: attr_accessor_with_default
This ActiveSupport method allows you to set a default value for an attribute accessor:
class Person
attr_accessor_with_default :age, 25
end
some_person.age # => 25
some_person.age = 26
some_person.age # => 26
You can even pass in a block.
2 tags
Random Array Item
From 1.8.7 on, there is the Array#shuffle method.
[1,2,3].shuffle # => [2,1,3]
This makes it extremely easy to write Array#random to pick a random item from an array
class Array
def random
shuffle.first
end
end
[1,2,3,4,5,6,7,8,9].random # => 5
[1,2,3,4,5,6,7,8,9].random # => 1
[1,2,3,4,5,6,7,8,9].random # => 3
This tip was submitted by Justin Baker.
2 tags
Prevent String#split from throwing away empty...
The default behavior of String#split will throw away any trailing values if they are empty.
> "Hello,There,,".split(',')
=> ["Hello", "There"]
If you want to keep those empty trailing elements, pass a negative number for the second (limit) parameter.
> "Hello,There,,".split(',', -1)
=> ["Hello", "There", "", ""]
This tip was submitted by two-bit-fool.
December 2010
4 posts
1 tag
Delay your Javascript execution
There’s a Prototype helper method called delay, so you can more precisely say when something will happen.
For example, you can do stuff like this inside your RJS files:
page["old_element"].visual_effect :blind_up, :duration => 0.5
page.delay(0.5) do
page.replace :old_element, :partial => "new_element"
page["new_element"].visual_effect :blind_down
end
Check out the delay...
2 tags
Array#first and Array#last parameters
Did you know you can pass a number parameter to Array#first and Array#last?
x = [1,2,3,4,5,6,7,8,9,10]
x.first 5
=> [1,2,3,4,5]
x.last 2
=> [9,10]
This tip was submitted by Alfred Nagy.
1 tag
42
You know you can access the 42nd element of an Array like this:
my_array[41]
In Rails, you can also access this element with the forty_two method:
my_array.forty_two
Check out the Array#forty_two method.
1 tag
Big Numbers
Your number has too many zeros? In ruby you can make that more readable (and easier to write!) by using underscores:
moneys = 1_000_000.00
=> 1000000.0
November 2010
4 posts
3 tags
Spell: Dynamic Dispatch
Coming from java - from time to time it just has to be… “copy-paste-time”. You’re used to it:
puts "response.inspect: #{response.inspect}"
puts "response.error_type: #{response.error_type}"
puts "response.response: #{response.response}"
puts "response.body: #{response.body}"
But wait - this is Ruby! Let’s have some fun with that spell I read about: Dynamic...
2 tags
The Beauty of Collect
Being from c programming background, to get an array of some property from the objects, I used to write this in Ruby:
amount_array = []
for order in account.orders
amount_array << order.amount.some_operation
end
While a much cleaner way is to use Array#collect:
amount_array = account.orders.collect { |order| order.amount.some_operation }
This tip was submitted by zerothabhishek.
3 tags
Use OpenStruct for application configuration...
Every rails app I’ve ever built needs some sort of configuration, and I seem to be solving this problem a different way every time, which really bothers me. Today I learned about a new class called OpenStruct. Here’s how you could use it.
# in app_root/config/initializers/app_config.rb
require 'ostruct'
AppConfig = OpenStruct.new
AppConfig.default_email =...
2 tags
Deep clone
Ruby comes with an Object#clone method that lets you copy objects. But this method makes a shallow copy, i.e. a duplicate without copying any referenced objects.
Object#clone:
Produces a shallow copy of obj - the instance variables of obj are copied, but not the objects they reference.
If you need a deep clone of an object - i.e. a copy including referenced objects - the Marshal module is...
October 2010
3 posts
2 tags
Using Struct.new to quickly create classes with...
You can use Struct.new to quickly create a custom class and inherit accessor methods and the to_s method.
class Office < Struct.new("Place", :coffee, :cigarettes)
end
Now you can do:
o = Office.new
o.coffee = true
o.to_s
=> "#<struct Office coffee=true, cigarettes=nil>"
Check out the Struct class.
This tip was submitted by Marco Campana.
4 tags
Viewing a model in YAML
The default viewing of attributes, and their values, of a model instance in script/console is not friendly. Principally if this model has many attributes, like the below example:
> order = Order.last
> order
=> #<Order id:1069267068, completed_at: nil, adjustment_total: 0.00, number: "R678647441", created_at: "2010-03-29 18:55:11", token: "LhiLU2J8ouIGHMUrkFab", updated_at:...