Archive for September, 2007

String to number conversion in Ruby

19 Sep

When converting a string in Ruby to and in using the value’s to_i method it will do some interesting conversion.


  • ‘5’ becomes 5 — Cool
  • ‘I have 5’ becomes 0 — kind of a weird failure, 0 could be a perfectly fine conversion
  • ‘5 is five’ becomes 5 — Really odd behavior, but the conversion is done until an incorrect character is encountered.  After this the rest of the string is ignored.  So
  • ‘5 is 5’ becomes 5
  • ‘5,000’ becomes 5

Where this is helpful so far is when someone is entering text through the command prompt.  When a person enters text prompted from gets the new line added from the user pressing enter is included.  So if a user enters 5, then the gets string contains ‘5n’.  In most languages this would cause and issue, but with how ruby does it’s conversion of ‘5n’ becomes 5.

No Comments

Posted in Web/Tech


String Multiplication in Ruby

19 Sep

This is pretty interesting. In ruby you can multiply a string. So if you wanted you could write

puts ‘Repeat ‘ * 3

Which outputs:

Repeat Repeat Repeat

I like this and I do think it makes sense.  It does not work if you write

puts 3 * ‘Repeat ‘

Which I think is wrong because multiplication should be commutative.


Now doing this has somewhat caused a problem for concatenation though.  By multiplying string it is not clear what should happen when you do this.

puts ‘Repeat ‘ + 3

So ruby outputs an error, something that I’ve enjoyed recently in .NET has been that if you add or concatenate a string with another object the other object is automatically changed to a string, using the ToString method I believe. 

I would think that this is a much more common scenario than multiplying strings and therefore a bigger loss to productivity and readability of code.

No Comments

Posted in Web/Tech


First Ruby WTF

19 Sep

Well I was reading through Chris Pine’s Learn to Program and he made a curious statement about how money is handled when programming.

In practice, most programs don’t use floats; only integers. (After all, no one wants to look at 7.4 emails, or browse 1.8 web pages, or listen to 5.24 of their favorite songs…) Floats are used more for academic purposes (physics experiments and such) and for 3D graphics. Even most money programs use integers; they just keep track of the number of pennies!

Now does anyone actually do this in the outside of the Ruby world?  When I use .NET I use an ORM and I map to the SQL money column type to a decimal.  I’m somewhat interested to see what ruby does in this situation.