Jesus Diaz
Jesus Diaz

Reputation: 31

Upcase method not returning upcased string

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

Answers (2)

Ursus
Ursus

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 largereturns 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

mlovic
mlovic

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

Related Questions