0
我用下面的代碼掙扎:LAMBDA返回不同的值
- 我想一個方法來檢查是否字符串包含內容或沒有。
has_content = -> (a) { a!=nil && a.strip != ''} c = ' ' has_content.call(c) => false c.has_content => true
爲什麼是響應不同?顯然,我缺乏一些Proc/lambda的知識。
我用下面的代碼掙扎:LAMBDA返回不同的值
has_content = -> (a) { a!=nil && a.strip != ''} c = ' ' has_content.call(c) => false c.has_content => true
爲什麼是響應不同?顯然,我缺乏一些Proc/lambda的知識。
我相信在導致這種行爲的代碼中缺少一些東西。
has_content
沒有爲字符串定義的,所以除非你之前定義的,它應該引發錯誤
1.9.3p429 :002 > ''.has_content
NoMethodError: undefined method `has_content' for "":String
from (irb):2
from /Users/weppos/.rvm/rubies/ruby-1.9.3-p429/bin/irb:12:in `<main>'
作爲一個側面說明,這裏是你的代碼的替代版本
has_content = ->(a) { !a.to_s.strip.empty? }
而且這裏是一個例子
has_content.(nil)
# => false
has_content.('')
# => false
has_content.(' ')
# => false
has_content.('hello')
# => true
'c.has_content'應該拋出錯誤......你如何得到'true'? –
同意Arup! –
順便說一句。更多地道的方法來檢查空的內容將是'!(a.nil?|| a.empty?)'。 –