Ruby Language - Question about methods

Asked

Viewed 64 times

1

I have a question about the Ruby language:

class Carro

  attr_accessor :marca, :modelo, :cor

  # declaração do método dentro da classe
  def velocidade_maxima
    250
  end
end

carro = Carro.new
puts "insira marca carro:"
carro.marca = gets
puts "insira modelo:"
carro.modelo = gets
puts "insira cor:"
carro.cor = gets
puts "a marca é " + carro.marca
puts carro.modelo
puts carro.cor
# AQUI
puts "velocidade do carro é de " + carro.velocidade_maxima

I wonder why I can’t put string + carro.velocidade_maxima to display 250, while others can concatenate normally?

Would be the method velocidade_maxima inaccessible outside the class? If so, how do I access without being by attr_accessor?

1 answer

1


The error in your code is:

no implicit Conversion of Fixnum into String (Typeerror)

I mean, you’re trying to concatenate a number (250) in a string ("velocidade do carro é de"). To resolve this, you can convert the number to string:

puts "velocidade do carro é de " + carro.velocidade_maxima.to_s

Or interpolate the expression within the string itself:

puts "velocidade do carro é de #{carro.velocidade_maxima}"

See the code running on Ideone.com.


In the other attributes this problem does not happen because gets returns a string, and so concatenation occurs smoothly.

  • Thanks friend. I had also forgotten the possibility of interpolation. In case, gets will always return string or may be another type?

  • @Renan From what I saw in documentation, return is a string

Browser other questions tagged

You are not signed in. Login or sign up in order to post.