this looks more like a JS function than Ruby :)
Few things to notice:
- The variables are not used so you can rid of them
- There are a lot of
else nil which can be removed as a Ruby method would return nil by default
- You're using a ternary operator just to return
nil, again, you can avoid it
- This method is doing too many things: It's checking what kind of log it is and also display/formatting it
- Style note: In Ruby we use snake_case, so the method should be called
find_logs
You can avoid the repetition as already said and replace it with something like:
def find_logs(obj)
log_type = ["E", "T", "L", "Te", "Le"].detect do |type|
obj[type] && obj[type]["pkg"]
end
"@#{log_type} = #{obj[log_type]['pkg']}," if log_type
end
Now, this is not particularly pretty and it's still doing two different things but it may be good enough, and it removed the duplication.
I don't know the problem you're trying to solve but as we're in Ruby it would probably better to solve it with a class, e.g. something like this (not tested so it may not work):
class LogFormatter
LOG_TYPES = ["E", "T", "L", "Te", "Le"]
def initialize(obj:)
@obj = obj
end
def format
"@#{log_type} = #{pkg}," if log_type
end
private
attr_reader :obj
def pkg
@pkg ||= obj[log_type]["pkg"]
end
def log_type
@log_type ||= LOG_TYPES.detect { |type| obj[type] && obj[type]["pkg"] }
end
end
Now, bear in mind that depending what you're trying to do, it may be a bit overkill - but personally, I prefer to have a small class rather than having this "complicated" method in some other class with a completely unrelated responsibility.
te = obj[...]becomesmy_hash['te'] = obj[...]