4 ms·
>> There is no implicit type conversion between numeric, string or boolean types. >Ok. This is a good thing. Auto conversion is bad. One of the things I reall
by seasoup 15y ago
>> There is no implicit type conversion between numeric, string or boolean types.
>Ok. This is a good thing. Auto conversion is bad.
One of the things I really dislike about developing in Ruby is that I can't do
value = 5
"The value is " + 5
I get bitten by this at least 10 times a day while developing, usually either when dumping to the log, or writing into html. I can fix the problem really quickly now, but every time I get an error:
"r" + 5
"TypeError: can't convert Fixnum into String"
I think, yes, yes you can easily convert a Fixnum into a String.
"r" + 5.to_s
It just means I have to sprinkle .to_s everywhere in my code. Ridiculous!
- msy 15y agoJust use inline implicit conversion: "r #{5+3/2}"
- jamesbritt 15y agoIt's a lot more typing. :) If one really wanted that kind of behavior (and not getting errors when trying to add strings and number) you could make it so: class String def +(o) warn "You are adding a #{o.class} to a string." unless o.is_a? String "#{self}#{o}" end end for example. Whether this leads to other issues is left as an exercise for the reader and whomever ends up maintaining the reader's code.
- andrewcooke 15y agoplease can you explain what value = 5 "The value is " + 5 is supposed to do? at the moment i can't work out why it would be frustrating to be unable to type something that looks like a syntax error... (i'm assuming it has some meaning in a language i don't know, which i guess would mean php). edit: what does "say" mean in the reply below? print? evaluate? and does "later" mean in another statement? or replacing what was before?
- Miky 15y agoHe means that he can't say “value = 5” and then later say “"the value is " + 5”.
- stickfigure 15y agoThe problem is that his two lines of code got joined by HN's formatter (which needs two newlines for a real line break). Presumably his desired message was: value = 5 "The value is " + 5
- phaedryx 15y agoI see that as a feature. It looks like you're saying "I want to add numbers and letters together and Ruby complains." If you really want that value in your string, why not use "The value is #{value}"
- rat 15y ago"r#{5}" or in actual use something like "I have #{me.num_of_children}\n" much better then Auto conversion In python "I have " + str(me.num_of_sons) + "and " + str(me.num_of_daughters) +"\n" does get annoying