Why is this returning nil?

D

Dark Ambient

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
 
T

ts

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

print @level

outside a string, # is a comment :)

D> else


Guy Decoux
 
F

Farrel Lifson

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

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

Farrel
 
M

Matthew Smillie

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

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.
 
A

Alexey Vakhov

Hello!

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

Dark Ambient

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

Stuart
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top