10 Quick Ruby Tricks

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

The following is a guest post by Trevor McKendrick and originally appeared on his blog. Trevor is currently in the Ruby-003 class at The Flatiron School. You can follow him on Twitter here.

1. Set a default value for an attribute accessor:

1
2
3
class Person
  attr_accessor_with_default :age, 25
end

2. Try: invokes the public method passed as a parameter, but returns nil if it doesn’t exist

1
@person.try(:name)

3. Use grep to search the methods of an object:

1
2
>> Object.methods.grep /inspect/
=> [“inspect”, “pretty_inspect”, “pretty_print_inspect”]

4. Mark deprecated code with Kernel#warn

1
2
3
4
5
6
7
8
9
10
11
class Foo
    # DEPRECATED: Please use useful instead.
    def useless
        warn “[DEPRECATION] `useless` is deprecated. Please use `useful` instead.”
        useful
    end

    def useful
    # ...
    end
end

5. “Pretend” flag gives a dry run if you’re not sure what the Rails Generate command is going to create

1
>> rails generate model Blog -p

6. The operator =~ matches a String against a regular expression. It returns the position/index where the String was matched – or nil if no match was found:

1
2
3
4
5
6
7
8
9
/Quick/ =~ “Ruby Quicktips”
=> 5

# Order does not matter
“Ruby Quicktips” =~ /Quick/
=> 5

“Ruby Quicktips” =~ /foo/
=> nil

7. Check syntax without executing the program:

1
>> ruby -c filename.rb

8. In IRB, assign last evaluated expression after it runs

1
2
3
4
5
6
>> 2 + 5
=> 7
>> x = _
=> 7
>> x
=> 7

9. Create hash from array

1
2
3
>> arr = [:a, 1, :b, 2]
>> Hash[*arr]
=> {:a => 1, :b => 2}

10. Join elements in an array

1
2
>>[1,2,3,4] * “,”
=> 1,2,3,4
Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat