Reputation: 28164
Update: the much better answer has little to do with refactoring, but has to do with setting a default for empty keys. See the first answer- thanks a lot guys!
Hi folks, how would you refactor this?
if n=network_stats["b"]
network_stats["b"] = n +1
else
network_stats["b"]=1
end
I have a nagging feeling this can be done in 2 lines
Upvotes: 1
Views: 184
Reputation: 8459
This is a short and readable oneliner:
network_stats["b"] = (network_stats["b"] || 0) + 1
And a longer but maybe more readable and scalable (when more cases would be added in the future) version:
network_stats["b"] = case network_stats["b"]
when nil then 0
else network_stats["b"] + 1
end
Update: As a curiosity, this can work to:
network_stats["b"] += 1 rescue network_stats["b"] = 1
I would not use it personally.
Upvotes: 5
Reputation: 8100
You can use ||= operator to assign value if nil, e.g.:
network_stats["b"] ||= 1
Then you are sure that network_stats["b"]
has value so simple increment by 1:
network_stats["b"] += 1
Final code:
network_stats["b"] ||= 1
network_stats["b"] += 1
Upvotes: 3
Reputation: 304175
# do this when network_stats is defined
network_stats.default= 0
# to increment the network stats
network_stats["b"] += 1
for example
>> (network_stats={}).default= 0
=> 0
>> network_stats["b"] += 1
=> 1
>> network_stats
=> {"b"=>1}
Upvotes: 4
Reputation: 5721
Hey Ming you should have known about ternary operators
I think this might help you get around
network_stats["b"] = (n == network_stats["b"]) ? n + 1 : 1
Upvotes: 0
Reputation: 25659
I'm going to assume there is a slight typo in your code, and you meant to do a comparison instead of an assignment on the first line, like this:
if n == network_stats["b"]
network_stats["b"] = n + 1
else
network_stats["b"] = 1
end
I would refactor this into something like:
n == network_stats["b"] ? (network_stats["b"] = n + 1) : (network_stats["b"] = 1)
While Christians answer is more precise in terms of bytes used, I find it less readable, but that's simply personal opinion.
In case he removes his answer, it was:
network_stats["b"] = (n == network_stats["b"]) ? n + 1 : 1
Upvotes: 0
Reputation: 16629
network_stats["b"] = (n == network_stats["b"]? (n + 1) : 1)
hope this helps
cheers
sameera
PS : This is a good site for code refactoring
Upvotes: 3