Orie Orie - 2 years ago 68
Ruby Question

Setting a value to nil?

I've run into a problem in Ruby that I can't seem to find an answer online for.

I have a few forms, and on one of them, I'm trying to set the value of

if nothing is entered.

This is the relevant section for what I have right now:

puts "What is #{name}'s estimated age?"
age = gets.to_i

def set_nils
age = nil if age.blank?

I've tried a few different ideas, but nothing seems to change my final output (just printing age back) at all.

Answer Source

The problem is that if you enter nothing as your input and convert this \n to an integer, the value becomes 0 because:

irb(main):008:0> '\n'.to_i
=> 0

Therefore, you should change to this:

puts "What is #{name}'s estimated age?"
input = gets.to_i
@age = input > 0 ? input : nil

def set_nils
    @age ||= nil

Output with valid age (> 0):

irb(main):001:0> name = "Tim"
=> "Tim"
irb(main):002:0> puts "What is #{name}'s estimated age?"
What is Tim's estimated age?
=> nil
irb(main):003:0> input = gets.to_i
=> 8
irb(main):004:0> @age = input > 0 ? input : nil
=> 8
irb(main):006:0* def set_nils
irb(main):007:1>     @age ||= nil
irb(main):008:1> end
=> nil
irb(main):009:0> set_nils
=> 8

Output with invalid age (< 0):

irb(main):017:0> name = "Tim"
=> "Tim"
irb(main):018:0> puts "What is #{name}'s estimated age?"
What is Tim's estimated age?
=> nil
irb(main):019:0> input = gets.to_i
=> -1
irb(main):020:0> @age = input > 0 ? input : nil
=> nil
irb(main):022:0* def set_nils
irb(main):023:1>     @age ||= nil
irb(main):024:1> end
=> nil
irb(main):025:0> set_nils
=> nil
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download