itsh
itsh

Reputation: 1123

conditional statement not working as expected in Ruby

I have a method which takes 2-arguments - message to print on the screen and (default) value. If the default value is nil then I want just the message to be printed on the screen otherwise message should contain the default value in square brackets.

For example: If I pass method1("Hello" , ""), it should print Hello but if I pass method1("Hello", "User"), it should print Hello [User]:. But right now it printing only Hello even in second scenario.

Below is the piece of my code:

def method1(mes, value)
  val = ""
  begin
    if value == "" || "#{value}".to_i == 0
      val = ask(mes) do |ch|
        ch = true
      end
    else
      val = ask(message+" [#{value}]: ") do |ch|
        ch = true
      end
    end

    if val == "" then
      val = "#{value}"
    end

  rescue => e
    print "Except occured in method1(#{mes}, #{value}) "+e
  end

  return val
end

Upvotes: 0

Views: 208

Answers (3)

sa77
sa77

Reputation: 3603

try this

def func(mes, val = "")
  puts val.size != 0  ? "#{mes} [#{val}]" : "#{mes}"
end

Outputs:

func(123)             # 123
func("Hello")         # Hello
func("Hello", 123)    # Hello [123]
func("Hello", "test") # Hello [test]

Upvotes: 0

sahilbathla
sahilbathla

Reputation: 529

If you are using rails

value.blank?

If you are using only ruby

empty = input2.respond_to?(:empty?) ? input2.empty? : input2.to_s.length.zero?

as value.empty? will not work on numbers

Complete solution

def method1(input1, input2)
  result = input2.respond_to?(:empty?) ? !input2.empty? : input2.to_s.length > 0
  input2 = "#{ result ? input2 : '' }"
  puts input2.empty? ? input1 : "#{ input1 } [#{ input2 }]" 
end

method1('Hello', '')
method1('Hello', 2)
method1('Hello', [])
method1('Hello', [2])
method1('Hello', {})
method1('Hello', { a: 2 })
method1('Hello', false)

#Output
Hello
Hello [Mr]
Hello [2]
Hello
Hello [[2]]
Hello
Hello [{:a=>2}]
Hello [false]

Upvotes: 0

Uri Agassi
Uri Agassi

Reputation: 37419

That's because to_i returns 0 for every string which is not a number:

"User".to_i == 0
# => true

So, in your code:

value = "User"

if value == "" || "#{value}".to_i == 0
  puts "was here"
end
# => "was here"

You should change your condition, perhaps to check if value is nil or empty:

if value.nil? || value.empty?

If you are using Rails, you can use the blank? method:

if value.blank?

Upvotes: 2

Related Questions