Last Updated: February 25, 2016
·
804
· mcansky

Strange case use

Reading a bit into Rubber code I discovered a strange case use (https://github.com/wr0ngway/rubber/blob/master/lib/rubber/cloud/aws.rb) :

case arch when /i\d86/ then "i386" else arch end

So I wondered why such a code base, with several different authors, would have a line such as this one that is, to my liking, not so Ruby like. Better benchmarks ?

So I ran small benchmarks using Ruby own Benchmark module : https://gist.github.com/4648380 .

Results are interesting :

#                       real
# case      : i486      (  0.000257)
# if (match): i486    (  0.000900)
# ? (match) : i486    (  0.000584)
# if (=~)   : i486       (  0.000220)
# ? (=~)    : i486      (  0.000228)
#                       real
# case      : ia64      (  0.000246)
# if (match): ia64    (  0.000305)
# ? (match) : ia64   (  0.000266)
# if (=~)   : ia64       (  0.000209)
# ? (=~)    : ia64      (  0.000229)

So not the benchmarks.

Any ideas ? Because to me the if or even the ternary operator looks way nicer than that case :

case arch when /i\d86/ then "i386" else arch end
# VS
arch =~ (/i\d86/) ? "i386" : arch

Don't you think ?

2 Responses
Add your response

Readability, no?

over 1 year ago ·

@NIA readability is often a subjective topic, still, for something like this particular line most ruby style guides would probably point towards the ternary operator ?: (https://github.com/bbatsov/ruby-style-guide#syntax)

Of course the case line is quite close to pure english I suppose and would be read easily by anyone. Regarding this I do appreciate the transparent regex match the case provides.

over 1 year ago ·