4 ms·
Regarding copy/pasting, I do agree. Not much of a point in reading if you're just going to do that. But, I was having a problem with exercise 4 and so copy/pas
by reaganing 15y ago
Regarding copy/pasting, I do agree. Not much of a point in reading if you're just going to do that.
But, I was having a problem with exercise 4 and so copy/pasted it from the webpage (removed line numbers with TextMate's vertical selection easily enough). Received the same error when trying to run it as I did when I typed it myself:
ex4.rb:10:in `+': can't convert Fixnum into String (TypeError)
from ex4.rb:10:in `<main>'
I'm not familiar enough with Ruby to understand why it's doing that... my googling shows similar ruby tutorials with that format, but one site I found suggested using #{variable_name} instead of the " + variable_name + " and that worked just fine for me.
Is this a real error in the book or something weird going on with my computer (OS X Lion w/ Ruby 1.9.2 installed)?
Great book, by the way.
- GaltMidas 15y agoCouldn't get your way to work, it blew off the rest of the string. Managed to get it to work by calling .to_s on each variable. Wondering if I did something wrong. I have your same setup and I'm a complete Ruby Noob.
- reaganing 15y agoto be clear, my line 10 looks like this: puts "There are #{cars} cars available." But, yeah, complete Ruby noob here as well so I don't really know what's wrong.
- danso 15y ago>10 puts "There are " + cars + " cars available." Yes, this will throw an error in Ruby because of line 1: >1 cars = 100 Ruby does not allow the mixing of integers and strings. So, as mentioned, you can invoke the .to_s method. Or you can interpolate the variables as you have done so with #{cars} inside double quotes.
- reaganing 15y agoThank you, that makes sense.
- getsat 15y agoInterpolation actually calls #to_s on the object, so if object.respond_to?(:to_s) returns true, you can use use it inside #{} in any kind of string that allows interpolation.
- grossvogel 15y agoWhen I read exercise 4, I thought, "I can't believe Ruby made the same mistake as Javascript!" Glad to learn this particular type of foot shooting is not possible in Ruby.
- msluyter 15y agoAlso a ruby newb, so I'm not sure, but I think it's an error in the book. I got that error on all versions of ruby I tried. Either var.to_s, or "blah #{var} blah" works for me. This seems to explain it: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/217432 http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/...
- rsobers 15y agoAh, I should fix that example. It's totally wrong. Nice catch! In hindsight, I probably should have used "Hello #{name}" style string interpolation in all of the examples since thats the idiomatic way of doing things. I was trying to expose the newcomer to multiple ways of manipulating and concatenating strings, but since the aforementioned way is almost always best, I should stick to that.