Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 134 ยท Practice

Common Ruby Mistakes

The Ruby mistakes everyone makes, with real error messages. Nil errors, shared defaults, string aliasing, scope and procs, and the fix for each.

Most Ruby bugs are not exotic. The same dozen mistakes show up in beginner code, in code written by people who just arrived from another language, and now and then in code written by experts who were in a hurry. Once you can recognize them by the error message, you fix them in seconds instead of minutes.

This lesson walks through the most common ones. For each, you see the mistake fail with the real Ruby 4.0 message, understand why it happens, and learn the fix. Read the messages carefully: Ruby's error messages are some of the most helpful in any language, and since Ruby 3.4 they show the exact part of the line that failed.

Mistake 1: calling a method on nil

This is the most common Ruby error by a wide margin. A variable, a hash lookup or a method returned nil, and your code treated it as if it were a real object.

Ruby NoMethodError on nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program stops with undefined method 'upcase' for nil (NoMethodError) and points a caret at .upcase. Ruby is telling you that name is nil, not that upcase is missing. The real mistake is one line earlier: the hash is keyed by strings, and the lookup used a symbol, so it found nothing and quietly returned nil.

The fixes depend on what you mean. If the value must exist, use fetch, which fails at the real problem. If it may be missing, use safe navigation (&.) or a default. See Hashes and Ternary, Safe Navigation and Short-Circuit.

Ruby Fixing nil errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

fetch is the strict choice, &. and || are the forgiving ones. Pick strict when a missing value is a bug, and forgiving when it is normal. Never sprinkle &. everywhere "just in case": it hides the real error, and the nil travels on until something far away explodes.

Mistake 2: mixing strings and numbers

Ruby does not convert types behind your back. Python and Java programmers sometimes expect "Total: " + 5 to work, and JavaScript programmers expect it to produce "Total: 5". Ruby raises.

Ruby TypeError when adding a number to a string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The message is no implicit conversion of Integer into String (TypeError). Ruby only converts implicitly when an object says it behaves like a string (to_str), and integers do not. The reverse order gives a different message: 5 + "5" fails with String can't be coerced into Integer, because here the integer is asking the string to act as a number.

Use interpolation, which calls to_s for you, or convert explicitly.

Ruby Interpolation and explicit conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line shows a second trap. "12abc".to_i quietly returns 12 and "abc".to_i returns 0, so a typo in user input becomes a valid-looking number. Integer("12abc") raises invalid value for Integer(): "12abc" (ArgumentError). Use the strict forms for anything that comes from outside your program.

Mistake 3: shared mutable defaults

This one is subtle because nothing fails. The program just gives wrong answers.

Ruby One shared default object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Hash.new([]) creates one array and hands out that same array for every missing key. shared[:a] << 1 does not store anything under :a; it mutates the shared default, so the hash is still empty ({}), every missing key now looks like [1, 2], and size is 0. Array.new(2, []) has the same shape: both rows are the same array object, so a change to one shows in the other.

The fix is the block form, which runs once per key or per slot and so creates a fresh object each time.

Ruby The block forms create fresh objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby is kinder than Python here. A default argument like list = [] is evaluated on every call, so add_item(1) and add_item(2) each get their own empty array. The trap exists only for objects you create once and share, such as Hash.new([]), Array.new(n, obj) and constants.

Mistake 4: two names, one string

Variables hold references, not copies. When you assign one variable to another, both point at the same object, and a mutating method changes it for both.

Ruby Aliasing and mutation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

original became "ruby!" although we only changed alias_name. Methods that end in ! or << mutate; most others return a new object. When you need an independent copy, call dup (see Copying Objects). When you want to guarantee nobody mutates a value, freeze it.

Ruby FrozenError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The message is can't modify frozen Array: ["ada", "grace"] (FrozenError). Freezing is shallow: the array is locked, but the strings inside it are not, unless you freeze them too. Notice also that a constant is not constant in the sense of other languages: Ruby lets you mutate the object a constant points to, and only warns if you reassign the constant itself. Freezing is what actually protects it. See Immutability and freeze.

Plain string literals in Ruby 4.0 are "chilled": they behave as mutable, and "abc" << "d" works in a normal run. A future Ruby will freeze them. Write code as if they were frozen (build new strings with interpolation or +, or use String.new or +"" for a mutable buffer) and your code will survive the change.

Mistake 5: the wrong number of arguments

Ruby checks the count when you call a method. The message points at both the call and the definition, which makes it easy to fix.

Ruby ArgumentError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get wrong number of arguments (given 1, expected 2) (ArgumentError). Ruby 4.0 prints the caller line and the callee line in separate blocks, which makes it obvious which side to change. Either pass the second argument or give it a default (greeting = "Hello"). For methods with many parameters, prefer keyword arguments (greet(name: "Ada")), which the error message names when one is missing: missing keyword: :greeting. See Method Arguments.

A related surprise is that blocks and procs are relaxed while lambdas are strict:

Ruby Procs are lenient, lambdas are strict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The proc fills missing arguments with nil, ignores extras and even unpacks a single array argument. The lambda behaves like a method. Most of the time you pass blocks, so the relaxed rule is what you want; just remember it when a block silently produces nil.

Mistake 6: expecting methods to see local variables

In Ruby, def starts a completely new scope. A method cannot see the local variables of the code around it.

Ruby NameError inside a method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get undefined local variable or method 'rate' for main (NameError). The error is worded as "variable or method" because Ruby does not know which you meant: a bare word is either a local variable or a method call with no arguments, and no such method exists. Blocks and lambdas, on the other hand, are closures and do see the surrounding locals (see Closures and Binding).

Ruby Passing the value, or using a constant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pass the value as a parameter, use a constant for true constants, or use a lambda when you really want to capture a local.

Mistake 7: return inside a proc

return means "leave the enclosing method". A lambda is its own little method, so return leaves the lambda. A proc has no method of its own, so return tries to leave the method where the proc was created, and that may be gone.

Ruby LocalJumpError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The result is unexpected return (LocalJumpError): make_callback already finished, so there is nothing to return from. Use a lambda when you want return, or use next inside a block to finish just that block call. See Procs and Lambdas.

Mistake 8: small gotchas that look right

Several mistakes produce no error at all. Here are the ones that bite most often.

Ruby Silent gotchas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Going through them: in bump_wrong, count = count + 1 creates a local variable named count on the left, and that new variable is nil on the right, so Ruby complains that + is undefined for nil. Use self.count = ... or self.count += 1 for setters. Next, result = yes and no parses as (result = yes) and no, so result stays true; use && in expressions and keep and/or for control flow. Deleting from an array while you iterate over it moves the remaining items under the index, so [2, 4, 6, 8] ends as [4, 8]; use reject!, delete_if or build a new array. The last two groups are about return values: each gives back what you iterated over, map gives back the results, and a method ending in puts returns nil. Finally, integer division truncates and floating point is binary, so compare floats with a tolerance or use Rational or BigDecimal for exact decimal math (see Numbers).

Mistake 9: rescuing too much

Writing rescue Exception catches everything, including SystemExit (from exit), Interrupt (Ctrl+C) and NoMemoryError. Your program can no longer be stopped politely. A bare rescue catches StandardError and its subclasses, which is almost always what you mean. Better still, rescue the specific class you can actually handle, and let everything else crash loudly. A swallowed exception (rescue; end) is the worst bug generator in Ruby: the failure vanishes and the symptom appears somewhere else, hours later. See Exceptions.

Never write an empty rescue. If you really want to ignore one specific error, name it and say why in a comment. At least log the message.

A debugging habit that finds most of these

When something looks wrong, check the facts before you theorize. p value shows the exact shape, value.class shows the type, and value.frozen? and value.equal?(other) answer the questions behind the mutation bugs above. In nine out of ten cases, one p shows the nil or the shared object you did not expect. See Debugging Ruby for more tools.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Hash.new([]) followed by h[:a] << 1 leave h empty?

    The default is one array object returned for every missing key. Appending to it changes that shared object but does not add the key. Use Hash.new { |h, k| h[k] = [] } instead.
  2. 2. What does "Total: " + 5 raise?

    Ruby never converts an Integer to a String implicitly. Use interpolation ("Total: #{5}") or to_s.
  3. 3. Why does a method not see a local variable defined outside it?

    def is a scope gate. Blocks and lambdas are closures and keep the surrounding locals, but methods do not.
  4. 4. After numbers = [2, 4, 6, 8]; numbers.each { |n| numbers.delete(n) if n.even? }, what is numbers?

    Deleting shifts the later items down while the iteration index moves on, so every second item is skipped. Use reject!, delete_if or select to build a new array.
  5. 5. What is the best way to stop "12abc" from silently becoming 12?

    to_i accepts any leading digits and returns 0 for garbage. Integer() is strict and raises ArgumentError for invalid input.

Summary

  • A NoMethodError ... for nil means a value you expected is missing; find where the nil came from, and use fetch, dig, &. or defaults on purpose.
  • Ruby never converts types implicitly in +: use interpolation or to_s/to_i, and the strict Integer() and Float() for outside input.
  • Hash.new([]) and Array.new(n, []) share one object; use the block forms.
  • Assignment copies references. Use dup for copies and freeze for protection, and remember that both are shallow.
  • def starts a new scope; blocks and lambdas are closures; return in a proc leaves the method that created it.
  • Setters need self., and is not &&, never delete from an array while iterating over it, and never write an empty rescue.

Next: Ruby for Developers from Other Languages