Skip to content

Instantly share code, notes, and snippets.

@stephaneliu
Last active May 7, 2017 21:11
Show Gist options
  • Save stephaneliu/7b6531131d11e5ab3a085bc7a6c4d0b2 to your computer and use it in GitHub Desktop.
Save stephaneliu/7b6531131d11e5ab3a085bc7a6c4d0b2 to your computer and use it in GitHub Desktop.
# Before
class CustomQuery
def levels
@levels ||= { 'a' => :low, 'b' => :med, 'c' => :high }
end
def current(level)
levels.each_with_index { |avail_level, index| return avail_level[index] if level == avail_level[index] }
:low
end
end
# After
class CustomQuery
def levels
@levels ||= Hash.new('a' => :low).merge('a' => :low, 'b' => :med, 3 => :high)
end
def current(level)
levels[level]
end
end
@stephaneliu
Copy link
Author

stephaneliu commented May 7, 2017

Refactor provides several improvements.

The refactored levels method initializes the Hash with a default for a missed key search. This change clumps the intent and rule of levels closer to each other. In contrast, the first examples provides a default for levels on line 9.

Secondly, the current method obtains the desired value using a more succinct element reference method. Finally, this method also removes the multiple exit points from method - the 'return' in the each_with_index block and the default ':low' value when not found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment