Satchel
Satchel

Reputation: 16734

more DRY and succinct way to write this ruby unless statement?

I have the following:

unless parsed['PREDICATE'].nil?
    predicate = parsed['PREDICATE']
end

The logic is clear here. But as I write it, just wondering if there's something equally clear, but more DRY?

Upvotes: 1

Views: 47

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can write it in one line :

predicate = parsed['PREDICATE']  unless parsed['PREDICATE'].nil?

Just a tip : Favor modifier if/unless usage when you have a single-line body.

Or, a guess, if you are checking if a key exists, and then assigning the value of the key to the var, then you might consider:

predicate = parsed['PREDICATE']  if parsed.has_key? 'PREDICATE'

Upvotes: 3

Related Questions