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.
2 comments
Posted in Ruby on rails
Written on Mon, 05 May 2008 at 5:21 am
Tags: Ruby programming
If you liked this post, then consider subscribing to our full RSS feed.
July 12th, 2008 at 9:14 am
Hi Rimpy. I was in Satish’s 5th batch and am now teaching in the 6th.
I wrote an explanation of the modulus operator to the students in the forums and also put the explanation on my blog. If you would like to read it, you can at this page of my blog. I hope it explains the modulus operator to your satisfaction; I’ve had many positive comments on it in class. 
July 14th, 2008 at 2:52 am
Hi Jeff, Thanks for that. Actually, i am very busy with my working schedule. Learning symfony to satisfy my client’s need. That’s why couldn’t find much time to explore about ruby. But i would like to go thourgh your post and will continue to explore on ruby.