January 13, 2016 by Daniel P. Clark

101 Ruby Code Factoids

0) ‘methods’ method

Since almost everything in Ruby is an Object you can type dot methods on it to see what methods are available.

1) _

In IRB the use of the underscore variable _ will hold the evaluation of the last line of code executed.

When the variable is used in code it’s an indicator from the developer that this parameter isn’t going to be used.  For example “Divided into columns of 4”

In the Minitest framework, starting in version 5.6.0, the use of underscore is an alias to the new spec style testing.

2) instance_exec

The instance_exec method is available on every Object, and everything in Ruby is an Object, and when you use it you open up the singleton_class of the object to work on.  Anything you can do in a Class you could do in an instance_exec.

You can even use this on a Proc… which could drive people crazy if you do.  But just so you know that you can, here it is.

3) Enumerator::Lazy

An Enumerator::Lazy object will give you back one object at a time from your collection with optional processing on each item.

4) Struct has Enumerable as its ancestor

Since Struct has Enumerable as its ancestor you can use any method from it and write some handy methods on Structs themselves.

5) $:

The $: variable is the load path for Ruby gems.  Also available via $LOAD_PATH.  You can add the current directory to your load path with:

6) inspect

The inspect method is meant to be a human readable representation for any object.  It is the default representation of an Object when you call Class#new and it shows it on the next line.

7) Hash#invert

Reverse your Hash key-value pairs.

8) Method#to_proc

You can convert methods to a proc.  Note they may be exclusively scoped to the same kind of Object they were defined in.

9) module_function

module_function is to a Module what private is to a ClassClarification: when included.

For writing your own private methods in a module see my blog post: Private Module Methods in Ruby

10) require_relative

require_relative is a convenient way to load other ruby files relative to your current files location.

11) instance_methods

On any class you can call the instance_methods method to find out what the individual instances of the class will have defined on them.

12) Enumerable

Enumerable is a module that is included in basic collection types such as Array, Hash, and Struct.  So all of these object types will include the instance methods from Enumerable.

13) defined?

The defined? method keyword is handy for checking whether anything is publicly defined module, class, method, etc.  On classes on modules you can also call method_defined?, public_method_defined?, private_method_defined?, and protected_method_defined?

14) –noprompt

If you execute IRB with the command line flag –noprompt you will enter in to an IRB session with none of the extra characters showing up on the left side of the terminal.  This is great if you want to experiment with code and then use your mouse to copy & paste from it.

15) string % value(s)

You can insert with type conversion into strings using the percent % method.

16) ternary operator _ ? _ : _

When you use a question mark after something with some space it starts an if else switch.  If the value before the question mark is true then return the first item after the question mark.  If false then move past the colon mark.

Is is generally advisable to use just one ternary operator per line.  If you wish to use more you should add parenthesis around each inner expression to allow for ease of comprehension.

17) ruby -e “#code”

Run ruby code snippets from the command line

18) %[]

%[] is just like using quotations to form a string.  It allows you to use interpolation, double quotes, and single quotes within.

19) erb

ERB is an included library with Ruby and you can use it to add Ruby code to other documents/strings.

20) undefined Class instance variables don’t raise errors

When a variable hasn’t been defined yet and you use the class instance variable form of an at symbol (@) then it will evaluate as nil rather than raising any “undefined” errors.

21) UnboundMethod

You can extract an instance method from a class and use it like a stand alone Proc with bind.

22) ObjectSpace

You can get get a reference to every instance of a specific object with ObjectSpace.

23) freeze

Once you freeze an object it cannot be modified.

24) ‘self’ can optionally be replaced by the object name

25) Top level scope objects can be accessed with ::

26) prepend

prepend adds a module to the most recent chain of class ancestors.  Those methods will be called first.

27) super

super calls the current methods name up the ancestor chain and continues until it finds the definition.

28) arity

arity lets you know how many parameters a Proc or method will take.

29) cloning Arrays

When you use the Array#clone method you end up with a different Array with the same exact Objects in them.  No additional memory will be used for the internal objects.  Array#dup will do the same thing.

If you modify the Array itself you don’t have to worry about the other Array being effected.  But if you change an object in the Array internally that object will be changed in both Arrays.

30) Default value for Hash

Just like above where duplicating an Array points to the same objects, so also we have the same object returned when we set a default for the Hash.

To remedy this it’s best to use default_proc to create a new Array each time.

31) class_eval with included

Using class_eval when you’re writing methods to be included is the more natural way of updating classes.  You’ll write your definitions just as if you’re in the class.

32) inherited

When you’re having one class inherit from another class as a “mixin” you can write an inherited hook.

33) %x

You can run external commands with %x{}.  %x can have any grouping symbols around its content: eg: ”, “”, {}, [], //, (), ^^.  Ruby’s percent methods typically allow all of these and more (most any non-alphanumeric character).

34) break :value

You can return a value out of a loop with break just like you would with return.

35) Lonely Operator &.

As of Ruby 2.3.0 there is a new operator known as the Safe Navigation Operator, or the Lonely Operator.  According to Matz it “looks like someone sitting on the floor, looking at the dot.”  What this operator allows you to do is continue chaining methods even if one of the items along the way returns nil.  It will safely return nil if that is the case.

Notice we didn’t get a NoMethodError.  This will save a lot of the uses of the Rails try method.

36) Hash#to_proc

Mapping values in Ruby is fairly common.  As of Ruby 2.3.0 they’ve added Hash#to_proc.

Anytime you place an ampersand symbol before an Object as a parameter it calls the to_proc method on the Object.  You can mimic the behavior above in earlier versions of Ruby by using the method method.

37) retry

In any begin/rescue/end block you can use retry to repeat the code execution within the block when an error is raised.

38) raise

raise can take 3 different parameters.  Just a text explanation, an Error class & a text explanation, or an Error class & text explanation & where the error is from.

Note you’ll probably want to use file and line info for the from area.

39) __FILE__

The current file.  In irb this will return “(irb)” .

40) __LINE__

The current line.

41) Hash.[]

42) Global Variables

The dollar sign defines global variables. ($)  Please don’t use them.  It will kludge up your code.  Constants can be used as global variables.  When possible use constants or objects to contain values you need.  APPLE is a lot nicer to see than $apple .  If you need to define APPLE globally just use ::APPLE

43) $0

$0 (dollar-zero) is the root file executed in Ruby.  It can be used like Python’s __name__ == “__main__” to only run code if this file is the main file.  Avoid running code when the file is required with this.

44) case permits then

45) case doesn’t need a value

46) case then is optional

47) case calls the === method

48) tail conditions

You can put your if statements and rescue statements after code.

49) use of return

In Ruby the last thing evaluated is automatically the returned object.  The only time you need to use return is if you want to exit with a value earlier in the code.

50) String#chars

The chars method will automatically split your string into individual String characters in an Array.

51) to_enum, enum_for, each, lazy

On any Array you can call any of to_enum, enum_for, each, or lazy methods to return an Enumerator Object that you can iterate over.  You have basic methods :next, :peek, :feed, and :rewind for each of these Enumerators.  But with Lazy you also get a :force method which returns the original collection.

52) curry

You can create additional Proc objects that set some of the parameters on another.

53) mandatory keyword parameters

54) Range inclusive and exclusive

55) String#upto

The upto method for String uses the strings ordinal values to build the range.

56) String#squeeze

The squeeze method on String objects brings gaps down to one in length.

Clarification: This doesn’t just squeeze spaces.  When no parameter is given it squeezes all duplicate neighboring characters.

57) String#replace

The replace method is unusual as it allows you to rewrite the string inside itself.

58) Infinity

You can count up to infinity… but you should do it lazily.

59) Enumerable#detect

You can use the detect method to return the first item that evaluates as true.

60) Enumerable#grep

You can use the grep method to find items in an Array that match your expression.

61) Method#owner

You can discover which object defines a method within the objects ancestry.

62) String#tr

Replaces all characters that match in place.

63) String#tr_s

Replaces all characters that match and squashes groups.

64) Array building

Using Kernel#Array to safely enforce an Array result along with using a class variable to avoid any errors creates for a clean looking and less redundant Array builder.  The << method appends a to the end of the Array.

A more common form is as follows:

But I find this far more cryptic looking and not as newbie friendly.  Readability, simplicity, and beauty are all important.

65) spaces

You can put spaces in between method calls and new lines after periods.

66) function one liners

With a semicolon you can avoid the need for adding extra lines.  Best for when you need to have many “short” functions defined.

67) Forwardable#def_delegators

You can pass method calls forward (to another object) with the Forwardable standard library module.

68) unless

unless is the same thing as if not (as it’s understood in English).  So whenever you see it – think “if not” and that should help.  If you aren’t accustomed to this it can be confusing.  The use case for unless is: you want a positive response for a negative situation.

 

69) superclass

You can use superclass to access the class inherited from.

70) binding an UnboundMethod

Continuing from the code above in #69 .

When instance_method(:foo) is invoked above it returns an UnboundMethod.  UnboundMethods can only be used in the same kind of Object they were defined in.  But first they must be bound.  To do this we used bind(self) inside an instance_exec .  Then to call it we run it as we would a Proc object with the call method.

71) alternative code continuation with \

If you don’t like entering new lines after a period, you may use a backslash.

72) HEREDOC

Multiple line strings.

The dash () is needed if you want to indent the ending of your HEREDOC closer.

As of Ruby 2.3.0 they’ve added the squiggle (~) option to remove leading white space. Note: It’s called a tilde and not squiggle.

You can use any up-cased string for marking the beginning and ending of your HEREDOC as long as they’re the same at both ends.

73) Hash#dig

As of Ruby 2.3.0 you now have a dig method great for getting deep into nested hashes.

74) dynamically naming classes

Ruby is full of ways to dynamically define methods.  But for classes there seems to only be the use of eval.  One way to define Classes is with eval.

I use the double colon here because in most cases you’ll be defining classes from within another class or module.  And if you want the classes to be available globally you’ll need to prepend the double colon ::

Another way to define a class is to use const_set.  (Credit to 0x0dea.)

75) addition doesn’t care

about excess symbol usage.  You can be artsy with code this way :-).

76) ~ tilde calls itself on the following Object

77) empty parenthesis () is nil

78) !!

Truthiness of Object.  Think of it as a double negative… it evaluates truth.

79) Ranges guess types

And it’s not always the right guess.

80) Symbols have methods too

81)  Numbers succ

82) %w and %W makes an Array of Strings

Like mentioned above in #33 most non alphanumeric symbols can mark the edges.

BONUS: %i and %I for Arrays of Symbols. (credit to tfaaft)

83) refinements are awesome

84) Procs keep their original binding

The following code is invalid.  The error demonstrates that even though the Proc is called from within an instance of Doctor that the Proc executes and evaluates directly from the instance of Cow.

To make the above work you’d need to have the new scope values brought into the Proc as a parameter.

85) Regex named matchers

86) included_modules

Beyond knowing the ancestry hierarchy with the ancestors method you can use the included_modules method for, as the name says, just seeing modules included.

87) at_exit

You can make code run as Ruby exits after the exit command.  Example from APIDock

BONUS: And

for running ASAP. (credit to 0x0dea)

88) ensure

ensure lets you make sure certain code gets run from within the block.

89) alias

You can give a method an additional name.

90) ENV

ENV is a variable holding a Hash of your systems environment variables.

91) Marshal

Convert Objects to Strings and back again with Marshal.

92) sleep

You can make your current thread sleep with calling sleep and providing in seconds how long to wait.

93) TAB

In IRB you can press the TAB key to autofill the rest of a constant or method name.  If there are more than one possibility it will list them all.

94) help

If you have your RI documentation installed then you can lookup information on methods in Ruby by typing help in IRB.

95) block_given?

block_given? is a method to determine if a block can be evaluated in the current scope.  Formerly iterator?

96) $>

$> is a global variable for STDOUT

97) $;

$; is a global variable that may change what strings split on by default.

It looks as though this feature is here to stay: Ruby Issue #11729

BONUS: And $, is the default for String#join (credit to 0x0dea)

98) warn

You can use warn to print a warning message to STDERR.

99) 1.0/0 is Infinity

100) Ruby has been around for 20 years!

THANK YOU!

Congratulations you have made it to the end of all 101 Ruby code factoids!  Let me know if you found this useful or insightful!  Thanks!

As always I hope you’ve enjoyed this!  Please comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

P.S. Thanks to everyone who’ve pointed out corrections on here and on reddit!  Reddit credits: tfaaft, Craftkorb, 0x0dea, and jb3689.

Image by Bram via the Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic License

#code#examples#factoids#ruby#things
  • Nice collection you have here 🙂

    It’s worth noting that `warn` prints to stderr instead of stdout, you can try that with `irb > /tmp/out`, type 1+1 then type `warn ‘test’`.

    The result: 2 will not be printed because stdout is being redirected, but ‘test’ will be printed on your screen.

    Here is an extra one for your collection: `__method__`.

    With `__method__` you can get the name of the current method, could be useful for meta-programming stuff.

  • Nunya Bidness

    Factoid means an “piece of information that becomes accepted as a fact even though it’s not actually true, or an invented fact believed to be true because it appears in print”, not a small fact.

    The things you posted here seem true though.

  • Pavel Pravosud

    iterator? is deprecated. you should use block_given? instead

  • Pavel Pravosud

    Also, ENV is not an Array, it’s a Hash-like object

  • Nice collection, amazing 😉

  • Wow, great work!

  • smolnar

    Might be obvious for some people, but it’s sure nice to point out that squeeze without parameters actually squeezes every character, not just space.

  • Carl Anderson

    Mention should be made about Hash.invert when there would be duplicate keys after inversion:

    h = {test: 1, tests: 1, testing: 2}

    {:test=>1, :tests=>1, :testing=>2}

    h.invert

    {1=>:tests, 2=>:testing}

  • Nice work!
    There were quite a few I hadn’t seen before

  • Nice list, thanks!

    1) _
    You can suffix it with a name if you want to keep the name around even if you don’t intend to use it:

    [/crayon]

    9) module_method
    What’s a

    ? Did you mean

    ?

    15) string % value(s)
    I’d call it formatting rather than type conversion.

    16) ternary operator _ ? _ : _
    Nah, never use more than one per line, with parens or not 🙂

    18) %[]
    You can use any non-alphanumeric character in place of

    , i.e.

    =

    =

    =…
    Unfortunately Ruby documentation is lacking in this department (and in some others), for example percent strings doesn’t explain the bare

    ; except the very implicit hint on

    🙂

    27) super
    Talking about

    , it might be worthwhile to mention the difference between

    and

    : http://ruby-doc.org/core-2.3.0/doc/syntax/modules_and_classes_rdoc.html#label-Inheritance.

    48) tail conditions
    Don’t hide exceptions, or they are going to bite you from where you can’t see them 🙂

    55) String#upto

    does the same thing. Also you don’t need

    in the second example as ranges,

    etc. already return an enumerator, e.g.

    =

    61) Method#owner
    Really useful!

    68) unless
    Regarding confusion, I replace it with an

    as soon as it makes me think about it.

    89) alias
    You may want to use alias_method instead: http://stackoverflow.com/questions/4763121/should-i-use-alias-or-alias-method

    91) Marshal
    Never pass untrusted data to

    (similar to

    , which had security issues in the past).

  • cn_jidong

    awesome !

  • Philippe Van Eerdenbrugghe

    Concerning `prepend`, it’s more subtle than that.

    Every class actually has a two half list of ancestors. One list “below” the class : the modules prepended tot the class and one list “above” the class : the modules included.

    When you call a method on an instance of the class, the method call will be tried on the “below” list, then on the class itself, then on the “above” list.

    This mechanism makes prepended modules really interesting to make `super` call and do something with the result. Actually that’s the main reason they were introduced, because it’s a much cleaner way to achieve this goal than the old `alias_method_chain`

  • 20 – an at-sign designates an instance variable, which does not always lie within a class. Therefore, calling it a class variable is not accurate.

    24 – I suggest removing this. Although true, it is best practice to use `self`, in case you ever change class or module names.

    54 – Also while true, it is much easier to do `(1..10)` (inclusive) and `(1…10)` (exclusive).

    56 – `#squeeze` does not remove gaps, but rather takes all repeated characters (“aaa”, “…”) and spits out a string with them replaced by a single char (“a”, “.”). No parameter acts on all duplicate instances, while a param searches for only that one.

    65 – True but would not recommend. If anything, you should separate long method chains by a new line, NOT spaces between the period!

    66 – tabular alignment is not ideal — http://wconrad.github.io/20150627/tabular-alignment-antipattern.html

    68 – `unless` is NOT the same as `if not`. The `not` keyword has lower precedence than `!method`. Rather, `unless` is the same as `if false`.

    79 – That’s because `’99’.next` is `’100’`. Unless defined elsewhere, how is Ruby to know that `’99’.next` is `’AA’`?

  • George Taveras

    I’m pretty sure 9) is not correct.

    a module module_function != a class private_method

    here is a gist explaining:
    https://gist.github.com/GeorgeTaveras1231/a673b23c37f969ba1f35

    You can say that module_function == single_methods. e.i. methods beginning with ‘self.’ inside a class or module, also known as class methods

  • I think it’s better to talk about alias_method as well
    And the difference between alias_method and alias

  • 97) maybe Array#join, right?

    cool doc, thanks!

  • dhalai

    Thx, it’s really interesting bundle 😉

  • Sean Snyder

    81. Numbers succ, also pred for reverse

  • Simone Bravo

    I’m not 100% sure about the 93)TAB in IRB

    • What version of Ruby are you using? The feature wasn’t always there.

      • Simone Bravo

        Sorry it was my fault, I’m using hyper.js and it has strange behaviours with everything.
        BTW great article you taught me lots of hacks, thank you.

  • Joshua Scott

    49 – this doesn’t work as written, the `x` isn’t in scope inside the `a` method

  • Billy.Zheng

    What the difference with:

    “`rb
    def do_the_lazy(array_input)
    Enumerator::Lazy.new(array_input) do |yielder, value|
    yielder << value
    end
    end
    “`

    and

    “`rb
    def do_the_lazy(array_input)
    Enumerator::Lazy.new(array_input) do |yielder, value|
    yielder.yield(value)
    end
    end
    “`