Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Jan 26 ’12

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 notes 0 comments

Jan 24 ’12

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 notes 0 comments

Jan 19 ’12

String#gsub with a block generates the substitution string dynamically

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 haystack?"

gsub can also take a block which can use all of the global match variables, such as $&, $', $1, $2, to build up a replacement string. This allows for replacement strings to be generated using information from the match, like this:

"Where is the needle in the nefarious haystack?".gsub(/n\w{5,}/) do
  '*' + $&.upcase + '*'
end
# => "Where is the *NEEDLE* in the *NEFARIOUS* haystack?"

Blocks provide gsub with the ability to generate the substitution string using information about a match that is only available after a match is identified. You can use any of the global variables associated with matches from within the block.

This tip was submitted by Tim Rand.

1 note 0 comments

Jan 17 ’12

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 in if-statements:

if "Ruby Quicktips" =~ /\s+/
  puts "The string contains at least one whitespace character."
end
# The string contains at least one whitespace character.
# => nil

To check the opposite, you can use the !~ operator:

if "Ruby Quicktips" !~ /\d+/
  puts "The string does not contain any digits."
end
# The string does not contains any digits.
# => nil

4 notes 0 comments

Jan 12 ’12

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

3 notes 0 comments

Jan 10 ’12

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", :option2 => "bar")
  # If you pass in options with the :option1 and :option2 keys,
  # their values will NOT be overwritten.
  # If you leave option1 and option2 out, the defaults passed
  # to reverse_merge will be inserted.
  # actual method implementation here
end

1 note 0 comments

Jan 5 ’12

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.)

4 notes 0 comments

Jan 3 ’12

Prevent rdoc and ri installation when installing a gem

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 this default per gem, or if you want to install the documentation later, you can do so by passing --ri and/or --rdoc options to the gem install command.)

The .gemrc file is the configuration file used by RubyGems, in which you can specify command-line arguments to be used every time the gem command runs: more about the RubyGems configuration file.

This tip was submitted by Andrea Singh.

6 notes 0 comments

Sep 14 ’11

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

(Source: rubyloveinfo)

10 notes 0 comments (via rubyloveinfo)

Sep 12 ’11

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 => :published_comments)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 1]]
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" IN (1) AND ("comments"."published" = 't')

Read more about this in the API docs about ActiveRecord::Associations.

4 notes 0 comments

Sep 9 ’11

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 methods. Check out these two post for more:

1 note 0 comments

Sep 7 ’11

Execute Ruby Code from the Command Line

This is the quickest way to execute ruby code:

ruby -e "puts 'Hello World'"

(Source: rubyloveinfo)

12 notes 0 comments (via rubyloveinfo)

Sep 5 ’11

Check the Syntax of a Ruby Script

This will check the syntax without executing the program:

ruby -c filename.rb

(Source: rubyloveinfo)

7 notes 0 comments (via rubyloveinfo)

Sep 2 ’11

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

14 notes 0 comments

Aug 31 ’11

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]

(Source: rubyloveinfo)

5 notes 0 comments (via rubyloveinfo)