On Thu, Nov 24, 2016 at 9:56 AM, Andy Jones <Andy.Jones / jameshall.co.uk> wrote:
>> Is there a better way to test if a variable|instance is empty ?
>> I usually use :
>>
>> @name = 'Guest' if @name.empty?
>
>
> I generally use something like
>
>     @name = (@name.nil? || @name.empty?) ? 'Guest' : @name
>
> Is that objectively better? Not really.

I think that highlights that using #empty? to detect "unset" is just
the wrong approach. Any variable is nil - unless assigned otherwise.
So it's much more easier to rely on nil as the unassigned state.
Compare

class C1
  def initialize
    @name = ""
  end

  def name
    @name = generate_name() if @name.empty?
    @name
  end
end

class C2
  def name
    @name ||= generate_name()
  end
end

For some arbitrary implementation of #generate_name.

If the empty string is some form of input then I think it should be
checked there right away, e.g.

def name=(s)
  @name = s if s && !s.empty?
end

or

def name=(s)
  @name = normalize(s)
end

def normalize(s)
  s.gsub(/\A\s+|\s+\z/, '').tap |x|
    raise "Wrong s" unless x.empty?
  end
end

But I'm digressing...

Kind regards

robert

-- 
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>