4

What I'm currently doing is

"Hello" if options && options[:greet]

What I would like to do is cut that line down. If options is nil, options[:greet] obviously will be too. Does Ruby/Rails provide a method that offers this "hash checking" ability? Or perhaps there's a way of writing this more succinctly?

Dan
  • 516
  • 5
  • 14
  • Possible duplicate of [How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?](http://stackoverflow.com/questions/4371716/how-to-avoid-nomethoderror-for-missing-elements-in-nested-hashes-without-repeat) – user513951 Feb 16 '16 at 20:22
  • 2
    I disagree with the duplicate - multi-level nested hashes is not what this question is about. – Taryn East Feb 16 '16 at 23:19

2 Answers2

7

There's also one more shortcut, I tend to use it more often, when I don't have control over options variable (i.e. it may be either nil or hash):

options.to_h[:greet] # just convert it to a hash before key access

Note, that it works only starting from Ruby 2.0.

Alexey Shein
  • 7,342
  • 1
  • 25
  • 38
6

I would argue that that line is perfectly fine.

Perhaps it might make sense to ensure that options are always set. If the options are passed in as a parameter to a method, you might want to set a default:

def method_name(options = {})

Or you might want to initialize options with an empty hash if nil before you start using them:

options ||= {}

Ruby on Rails also offers the try method that does not fail when you call methods on nil:

options.try([], :greet)
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Thanks, I was initializing with `options=nil`, and didn't really think about the possibility of setting it to an empty hash. Interesting use of `try` too :) – Dan Sep 14 '15 at 10:00