Back

10 Quick Ruby Tricks

Posted by Flatiron School  /  January 17, 2019

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:

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

@person.try(:name)

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

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

4. Mark deprecated code with Kernel#warn

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

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

/Quick/ =~ “Ruby Quicktips”
=> 5

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

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

7. Check syntax without executing the program:

>> ruby -c filename.rb

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

>> 2 + 5
=> 7
>> x = _
=> 7
>> x
=> 7

9. Create hash from array

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

10. Join elements in an array

>>[1,2,3,4] * “,”
=> 1,2,3,4

Ready to learn some Ruby for yourself? Start with Flatiron School's free introductory Ruby course.