String#blank?
は非常に便利ですが、RubyではなくRailsに存在します。Rubyの文字列#空白はありますか?方法?
は交換するRubyでそれのようなものが、あります:
str.nil? || str.empty?
String#blank?
は非常に便利ですが、RubyではなくRailsに存在します。Rubyの文字列#空白はありますか?方法?
は交換するRubyでそれのようなものが、あります:
str.nil? || str.empty?
AFAI K普通のRubyのようなものはありません。あなたはこのように独自に作成することができます。
class NilClass
def blank?
true
end
end
class String
def blank?
self.strip.empty?
end
end
これはnil.blank?
のために働くだろうと(レールがないように)a_string.blank?
あなたは真/偽と一般的なオブジェクトのためにこれを拡張することができます。
class FalseClass
def blank?
true
end
end
class TrueClass
def blank?
false
end
end
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
参考文献:
https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L57 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L67 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L14 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L47
そして、ここで以前のものよりも効率的でなければなりませんString.blank?
実装です:
その実装はより非効率的になる可能性があります。 「非常に長いストリング......」で試してみてください。 –
NilClassを拡張するのは悪い習慣ですか? –
@BSevenはい、このソリューションは、Railsメソッドが行うさまざまなオブジェクトでは機能しません。また、Marc-Andreによって指摘されているように、 'strip'は少し非効率です(特に出力を捨てるとき) –
あなたは常にRailsがまったく同じものを行うことができます。
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 14
def blank?
respond_to?(:empty?) ? empty? : !self
end
コードが 'respond_to?(:empty?) 'に調整されていることに言及する価値がありますか? !!空の? :!self'の新しいバージョンです。 –
んが、そのような機能はRubyで存在しませんが、ruby-core上String#blank?
のためのアクティブな提案があります:あなたはthe source to blank
を見れば、あなたはそれがObject
に次のメソッドが追加されます参照してください。一方
、あなたはこの実装を使用することができます
class String
def blank?
!include?(/[^[:space:]]/)
end
end
をこの実装は、非常に長い文字列のため、非常に効率的になります。
参考文献のようなものは表示されません。http://ruby-doc.org/core-2.0/String.html – shishirmk
いくつかの情報については、この回答を参照してください。http://stackoverflow.com/questions/4819899/rails -objectblank-vs-stringempty-confusion – squiguy
可能な重複:http://stackoverflow.com/questions/247948/is-there-a-better-way-of-checking-nil-or-length-0-of-a- string-in-ruby – christianblais