Reputation: 1
Can anyone help me with this simple exercise?
class Item
def percents()
self * 100
end
end
answer = gets.chomp
puts answer.percents()
The result is:
percents.rb:7:in `<main>': undefined method `percents' for "300":String (NoMethodError)
Upvotes: 0
Views: 468
Reputation: 9443
The variable answer
needs to be an Item
object in order to have the percents
method. Or, you can remove the percents
method from the Item
class, and have it take in an integer:
def percents(int)
int * 100
end
answer = gets.chomp
puts percents(answer)
This last line, however, won't do you as you would expect. Since gets.chomp
returns a string of your input, you'll be multiplying the string "300" by 100, which means your output will look like this:
2.2.2 :026 > puts percents(answer)
300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300
=> nil
You can first convert your answer to an int, using to_i
, and then print the percent
2.2.2 :027 > puts percents(answer.to_i)
30000
=> nil
There, that looks better. Now if you'd like make your answer
an object of class Item
, that's a bit more tricky.
class Item
def initialize(answer)
@answer = answer
end
def percents
@answer * 100
end
end
item = Item.new(gets.chomp.to_i)
puts item.percents
Your output will look the same as above:
2.2.2 :049 > puts item.percents
30000
=> nil
Let me know if you have further questions, as I'm not 100% sure of the intent of the program you're trying to write. I'd recommend checking out a few Ruby tutorials like Ruby in Twenty Minutes or Tutorial Point's ruby tutorial in your quest to learn Ruby. I hope this helps!
Upvotes: 2