Why is this returning nil?

class User

def initialize(level, status)
    @level = level
    @status = status
end

def finda
    if @status == "active"
        print #{@level}
    else
    puts "user not exist"
    end
end

end

user1 = User.new(1, “active”)
user2 = User.new(1, “inactive”)
user3 = User.new(2, “active”)
user4 = User.new(3, “inactive”)

user1.finda

Something wrong …not sure
TIA
Stuart

“D” == Dark A. [email protected] writes:

D> if @status == “active”
D> print #{@level}

           print @level

outside a string, # is a comment :slight_smile:

D> else

Guy Decoux

On 09/08/06, Dark A. [email protected] wrote:

    else

user1.finda

Something wrong …not sure
TIA
Stuart

print and puts return nil. As they are the last commands executed
their return statuses are returned.

Farrel

On Aug 9, 2006, at 17:23, Dark A. wrote:

   else

user1.finda

Something wrong …not sure
TIA
Stuart

Because methods return the value of the last statement. In this
case, both ‘puts’ and ‘print’ return nil, the actual output to the
screen is separate from the return value:

print “Hello\n”
Hello
=> nil
puts “Hello”
Hello
=> nil

My guess/advice would be to return the actual string you’re
eventually going to output, and deal with the actual output elsewhere
in the code.

matthew smillie.

2 things…

  1. Change “print #{@level}” to “print @level
  2. print and puts both return nil

Mark

Hello!

You forgot quotes in line print #{@level}. Change it to “print
#{@level}” please.

2006/8/9, Dark A. [email protected]:

Wow…lot of answers, thanks to all.
It works and I’ve learned a few things in the process.

Stuart

Oh. Some mistake. Change it to

print " #{@level}"

of course :slight_smile:

2006/8/9, Alexey V. [email protected]:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs