This is a personal memo.
By using the if statement and the present?
Or blank?
Methods, the process can be branched depending on whether the value is set in the variable.
In ruby, if can be written after (called postfix if). You can use this to make a simple description.
・ Object.present?
Returns true if object has a value.
・ Object.blank?
Returns true if object has no value or is empty.
There is no value for nil and empty ("").
If there is no value
irb(main):333:0> x
=> nil
irb(main):333:0> x.present?
=> false
irb(main):334:0> x.blank?
=> true
If there is a value
irb(main):335:0> test
=> "test"
irb(main):336:0> test.present?
=> true
irb(main):337:0> test.blank?
=> false
There are also nil? And empty? Methods that are similar to blank ?. The relationship between the object to be verified and the output is as follows.
Method | nil | empty ("") |
---|---|---|
blank? | true | true |
nil? | true | false |
empty | false | true |
present? | false | false |
If the value is empty
irb(main):340:0> z = ""
=> ""
irb(main):341:0> z.empty?
=> true
irb(main):342:0> z.nil?
=> false
・ Processing if conditional expression
Postfix if
def jadge(x)
"exist" if x.present?
end
Normal if statement
def jadge(x)
if x.present?
"exist"
end
end
python
def jadge(x)
y = "No" if x.blank?
y = "Exist" if x.present?
p "the answer#{y}is"
end
Recommended Posts