0

How do I create a condition inside a function that tests if a variable passed to a function is defined, and if it isn't, execute a command, otherwise execute the function?

sawa
  • 165,429
  • 45
  • 277
  • 381
MRG
  • 9
  • 1

3 Answers3

2

Something like this

def your_method(parameter)
  if parameter
    # do something
  else
    puts "parameter has no value"
  end
end
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • I tried this and got-> name error: undefined local variable, ...not sure where I went wrong. – MRG Jul 02 '16 at 13:19
  • 1
    @SlySherZ `0` is truthy in Ruby. – Aetherus Jul 02 '16 at 13:21
  • If the `parameter` could be a falsy value, like false, you'll need a more complex condition. Check: http://stackoverflow.com/questions/288715/checking-if-a-variable-is-defined – SlySherZ Jul 02 '16 at 13:36
1

You can do it like this:

def foo bar
  return puts "..." unless defined?(bar) == "local-variable"
  # Otherwise, continue with the method
  ...
end

However, the variable bar assigned to the given argument is always defined. The unless ... condition will never be satisfied. So your question does not make practical sense.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

(If you're using Rails) Use #try, see: https://github.com/rails/rails/blob/dd7d5b7c800b4f6d32747913fc7c8d00ce94f03a/activesupport/lib/active_support/core_ext/object/try.rb#L54

def my_function(var)

  return "string here" unless try(var)

  # --or--
  #
  # execute_whatevs unless @object.try(var)
  #
  # execute_whatevs(var) unless try(var) 
  #
  # execute_something unless try(var)
  #
  # var.try(:execute_whatevs)
end
SoAwesomeMan
  • 3,226
  • 1
  • 22
  • 25