Ruby - Return default value if variable is not present -


I often have to face the following issue: As long as it does not exist, I want to set a variable. Of course it can be done easily by doing this:

  var1 = "" var1 = "buzzer" unless that var1.present?  

If this was zero then it could be done with a simple = = operator, but when there is no empty string Zero This will not work I tried to read on Ruby or Operator, should work in principle:

  var1 = "" or "dhiughr"  

but it is not. << Code> Current

What am I doing wrong?

You can do this by method (which is the Active_support comes as an extension from the library ):

  var1 = var1.presence || 'Dhuhr'  

This works as you expect:

  var1 = '' var1 = var1.presence || 'Dhiughar' var1 # = & gt; "Dust" var1 = 'foo' var1 = var1.presence || 'Dhiughar' var1 # = & gt; "Foo"  

Comments