Since my ruby learning process, I was really surprised with POLS (Principle of least surprise). I have experience of so many langs but i never use ‘%’ operator for Strings, Arrays.
Evaluate the following expression:
1 | puts sprintf('%0.3f' % 3.351) |
results: 3.5
well i am fine with this result but what’s about single ‘%’ sign in above expression.
After some R & D, that is basically interpolating the second operand on first one. like if i do some thing.
1 2 | str_exp = "%s is going to his %s" puts sprintf(str_exp % ["Terry","office"]) |
Results: Terry is going to his office!
Amazing now ‘%’ is operating on string and array. That’s really cool.
One more point is making me surprise about ruby.
Evaluating the following expression:
1 | puts -5 % 3 |
well i was expecting -2. But ruby evaluated to “1″
why?
Will do more research on that.