Skip to content

Instantly share code, notes, and snippets.

@mhutter
Last active November 21, 2016 09:27
Show Gist options
  • Save mhutter/2aeb653dc4bec098ead6 to your computer and use it in GitHub Desktop.
Save mhutter/2aeb653dc4bec098ead6 to your computer and use it in GitHub Desktop.
Ruby quick patterns

Ruby Quick Patterns

Quick arrays

%w{foo bar baz}
#=> ["foo", "bar", "baz"]

Make sure we have an array

Array('foobar')
#=> ["foobar"]
Array(%w(foo bar baz))
#=> ["foo", "bar", "baz"]

Use case

Given the method do_something(*args), when we call do_something("foo"), args will be a String, but when calling do_something("foo", "bar"), we have an array. Using the above line, we always have an array.

Fallback values

sum = (foo || 0) + bar
sum = (foo or 0) + bar

Use case

foo = nil # foo MUST be initialized

# some code, which MAY set foo

foo + 42 #!=> NoMethodError: undefined method `+' for nil:NilClass
42 + foo #!=> TypeError: nil can't be coerced into Fixnum
(foo || 0 ) + 42 #=> 42

Background

|| or or are boolean expressions. The right-hand part of the expression only gets evaluated, if the left-hand part evaluates to false (which nil does!).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment