Is there a ruby ​​function? (Val) .nil ??

I often find myself in this:

!(val).nil?

My code will be prettier if there is a method like

val.exists?

Is there something similar?

+3
source share
5 answers

you can use an operator unlesslike

do_something unless val.nil?

which is probably pretty close to the ideal way of saying it: if you had a method non_nil?, you would have a negative expression instead of a positive expression like this.

+11
source
if !val.nil?
  # do something
end

# is equivalent to

if val
  # do something
end

If you use Rails, does ActiveSupport provide two object extensions called Object # blank? and object # present ?.

if !address.nil? && !address.empty?
# becomes
if !address.blank?
# which becomes
if address.present?
+5
source

, ! val.nil? , , , ; , , -, .

.nil? :

:

blah = {}
[:a,:b,:c,:a].each do |l|
     if blah[l].nil?
         blah[l] = 0
     else
         blah[l] += 1
     end
end
blah #=> {:a => 2, :b => 1, :c =>1}

,

blah = Hash.new(0)
[:a,:b,:c,:a].each{|i| blah[i] += 1} #or with inject.

||= - .


: - , nil, && , nil ,

if !val.nil?
   val.do_something
end

val && val.do_something # =>nil if val is nil, val.do_something value otherwise

, nil , mckeed (x, y) , .

+2

!! val

+1
module Nonnil
  def non_nil?
    !(self.nil?)
  end
end

class Someclass
  include Nonnil
  extend Nonnil
end

This will add a member .non_nil?to the class Someclassdefined as the inverse of .nil?. Mix this module with the class to which "val" belongs (in your example), and you will have a convenient shortcut. Mix this with the class Objectand it will be available for each class (since it Objectis the parent for all classes).

0
source

Source: https://habr.com/ru/post/1729132/


All Articles