Reputation: 31
I keep getting false in these simple Ruby tests:
def large(string)
if string.size > 20
puts string.upcase!
else
puts string
end
end
test:
p large("Hola vamos a la comida") == "HOLA VAMOS A LA COMIDA"
p large("Es hora de dormir") == "Es hora de dormir"
What is needed to make them work?
Upvotes: 1
Views: 64
Reputation: 30071
puts
prints on screen AND returns nil
. nil
and false
in Ruby, in a boolean context, are false
. Everything else is true
. So your method large
returns nil
. You should write it like this
def large(string)
if string.size > 20
string.upcase!
else
string
end
end
A better way would be
def large(string)
string.size > 20 ? string.upcase : string
end
Upvotes: 0
Reputation: 864
puts
prints its argument, but it's return value is always nil
:
> val = (puts "Hello World")
Hello World
=> nil
> val
=> nil
In your code, the return value of large
is always nil, so the comparison with a string
always returns false
.
This is probably closer to what you want:
def large(string)
if string.size > 20
string.upcase!
else
string
end
end
Upvotes: 4