こんなことがあります。
[2] pry(main)> a.nil? => false [3] pry(main)> a.empty? => false [4] pry(main)> (a.nil? or a.empty?) => false [5] pry(main)> a.blank? => true
なんだこのa
[6] pry(main)> a => " "
スッペース
ここにはっきりと書かれていますね。
Active Support Core Extensions — Ruby on Rails Guides
strings composed only of whitespace (see note below),
ソースも読んでみる。
[7] pry(main)> a.method(:blank?).source_location => ["/Users/ryonext/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/activesupport-3.2.15/lib/active_support/core_ext/object/blank.rb", 102]
class String # A string is blank if it's empty or contains whitespaces only: # # ''.blank? # => true # ' '.blank? # => true # ' '.blank? # => true # ' something here '.blank? # => false def blank? self =~ /\A[[:space:]]*\z/ end end
とあるので、spaceはアウトですね。
というか、先に正規表現の":blankがSpace or Tabである"という知識があればこの挙動はすんなり理解できたのに、と思いました。
これで困ったポイント
入力値としてスペース文字を許す仕様を作っていて、スペースだけで入力された値をblank?で判定したせいでうまく動かないということがありました。こういう場合は素直に (nil? or empty?) を使いましょう。