0

我有这个代码:

  def self.add_contact(name, phone, adress, note)

    if name.empty? || phone.empty? || adress.empty?
      puts 'some text'
    else
      Zoznam.new(name, phone, adress, note)
    end

  end

但我想要另一种方法,没有empty?方法。因为该empty?方法只能用于字符串而不是整数。什么是正确的方法?

对不起,我的英语不好...

4

3 回答 3

2

您可以使用activesupport实现blank?方法的gem。这可能正是您想要的。

于 2013-07-26T13:33:26.270 回答
1

Using.to_s.empty?应该涵盖你所有的情况,这似乎是 String、Integer 和 nil。

"".to_s.empty?    # => true
nil.to_s.empty?   # => true
"foo".to_s.empty? # => false
1.to_s.empty?     # => false
于 2013-07-26T16:13:45.680 回答
0

But I want another method, not the empty? method, because the empty method can be used only for strings and not integers. What is the correct method?

Well depends really on what you consider an integer empty. There's no such thing as empty? in the Integer class because it doesn't make sense. If your variable is of type Integer or Fixnum there's no way it is empty somehow: it will always contain a value, a number.

What I guess you are looking for is to test the variable phone for emptiness in the sense that nil might be assigned to it. In that case you can simply use:

if name.empty? || phone || adress.empty?

or

if name.empty? || phone.is_a? Fixnum || adress.empty?

if you want to be absolutely sure that phone is Fixnum (or any other class for that matter).

于 2013-07-26T17:37:46.907 回答