Ruby 是Rails方法。如果空字符串之间有空格怎么办?@StevenaGuillar空格被视为长度1(因为空格是字符)。“”。空白?=>False我更喜欢使用.reject(&:blank?)来避免将nil值作为well@RanGaliliblank?是一个不错

Ruby 是Rails方法。如果空字符串之间有空格怎么办?@StevenaGuillar空格被视为长度1(因为空格是字符)。“”。空白?=>False我更喜欢使用.reject(&:blank?)来避免将nil值作为well@RanGaliliblank?是一个不错,ruby,arrays,Ruby,Arrays,是Rails方法。如果空字符串之间有空格怎么办?@StevenaGuillar空格被视为长度1(因为空格是字符)。“”。空白?=>False我更喜欢使用.reject(&:blank?)来避免将nil值作为well@RanGaliliblank?是一个不错的选择,但它是一个rails方法,这个问题是关于普通的ruby看起来非常危险!如果你有像“纽约”或“Naujoji Akmene”这样的城市,这肯定会失败:)在Ruby 2.3.1上,我得到了NoMethodError:“未定义的方法`blan


是Rails方法。如果空字符串之间有空格怎么办?@StevenaGuillar空格被视为长度1(因为空格是字符)。“”。空白?=>False我更喜欢使用.reject(&:blank?)来避免将nil值作为well@RanGalili
blank?
是一个不错的选择,但它是一个
rails
方法,这个问题是关于普通的
ruby
看起来非常危险!如果你有像“纽约”或“Naujoji Akmene”这样的城市,这肯定会失败:)在Ruby 2.3.1上,我得到了NoMethodError:“未定义的方法`blank?'for 1:Fixnum”试图执行它。@Tom blank?是一种特定于Rails的方法。普通ruby的数组中不存在。你要用空的吗?或者编写您自己的方法。@jpgeek感谢您的澄清,这就是我在实现
:blank时遇到的问题?
是Rails特定的。因为
NoMethodError:undefined method empty?对于nil:NilClass
:空白
优于
:empty?
:blank
优于
:empty
。因为
:empty
不适用于
nil
['a',nil',b',''。选择(&:present?)
进行速记
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
noEmptyCities = cities.reject { |c| c.empty? }
>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 
puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
cities.delete("")
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)

=> ["A", "B", "C"]
[nil,"some string here","",4,3,2]
[nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}
=> ["some string here", 4, 3, 2]
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
cities.reject! { |c| c.blank? }
cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
[1, "", 2, "hello", nil].reject(&:blank?)
[1, 2, "hello"]
 cities.reject!(&:empty?)
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]

cities.select(&:presence)

["Kathmandu", "Pokhara", "Dharan", "Butwal"]
cities.delete_if(&:blank?)
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]

cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]
 ['a', nil, 'b'].compact  ## o/p =>  ["a", "b"]
   ['a', 'b', ''].select{ |a| !a.empty? } ## o/p => ["a", "b"]
['a', nil, 'b', ''].select{ |a| a.present? }  ## o/p => ["a", "b"]