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

8 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

4 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

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

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

8 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

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

6 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:

2 notes 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'"

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

8 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]

5 notes 0 comments (via rubyloveinfo)

Aug 29 ’11

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 "posts".* FROM "posts" WHERE "posts"."category" = 'tech' AND "posts"."author_id" = 1

The difference to dynamic finders (e.g. Post.find_by_category('tech')) is, that you can chain these together and add additional conditions - just like with any named scope:

Post.scoped_by_category('tech').all(:select => "id, title")
# => SELECT id, title FROM "posts" WHERE "posts"."category" = 'tech'

25 notes 0 comments

Aug 26 ’11

Step through your Cucumber features one step at a time

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.

1 note 0 comments

Aug 24 ’11

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"

1 note 0 comments

[フレーム]

AltStyle によって変換されたページ (->オリジナル) /