0

Let's say I have the following (working) pseudo-code:

puts results.fields.inject('') { |string, key|
  lengths[key] = calculate_length(key)
  string << format(key)
}

Following the ruby-style-guide I should

  • Omit parentheses for 'keyword methods', i.e. puts, (which would create }) or end) anyway)
  • Use do...end for multi-line blocks

However, when replacing {...} with do...end it raises

undefined method `' for :title:Symbol (NoMethodError)

Therefore, is it possible to refactor this code without violenting the guideline?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Frank
  • 33
  • 7

1 Answers1

0

There is a difference in precedence between {} and do end

If you use do end the block is associated with the puts statement, whereas the braces are associated with the results.field.inject('')

If you want to use do end then you have to remove the ambiguity of association by parentheses. It's one of those "gotchas" where the guidelines are recognized as guidelines, not absolute rules.

See also this answer...

In Ruby, why is a method invocation not able to be treated as a unit when "do" and "end" is used?

Community
  • 1
  • 1
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53