Last active
May 7, 2017 21:11
-
-
Save stephaneliu/7b6531131d11e5ab3a085bc7a6c4d0b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.