It appears you need to accommodate getting either a number or a string. There a number of ways to handle it, but one would be:
@price = pricefinder.to_s.gsub(',', '').to_i
Вопрос
With the following function, I go to a site, crawl some information, am returned some JSON, and put it into the @price
instance variable.
The JSON that is returned to me is a number, but if the number is greater than 1000, then the number will contain a comma, so I gsub it out.
def iteminfo(id)
url = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=#{id}"
page = Nokogiri::HTML(open(url))
info = JSON.parse(page.text)
namefinder = info['item']['name']
pricefinder = info['item']['current']['price']
name = namefinder
@price = pricefinder.gsub(',', '').to_i
end
I've already tried this:
if pricefinder.to_i > 1000
@price = pricefinder.gsub(',', '').to_i
else
@price = pricefinder.to_i
end
which gets rid of the error, but messes up the math that is performed on @price
How can I fix this?
Решение
It appears you need to accommodate getting either a number or a string. There a number of ways to handle it, but one would be:
@price = pricefinder.to_s.gsub(',', '').to_i
Другие советы
The error states that you're trying to call the method gsub
on an object of type Fixnum
(This tells me that you're dealing with strings and with numbers at the same time).
Something like this might work:
pricefinder.to_s.gsub(',', '').to_i