有没有一种比下面更简洁的方法来检查数组是否仅包含String类对象?
a = ['one','twon','three'] # => ["one", "twon", "three"]
b = ['one','twon', 1 ] # => ["one", "twon", 1]
c = ['one','twon', {one: 1} ] # => ["one", "twon", {:one=>1}]
def contains_only_string_class(object)
uniq_a= object.map{ |i| i.class }.uniq # => [String], [String, Integer], [String, Hash]
uniq_a.include?(String) & (uniq_a.length == 1) # => true, false, false
end # => :contains_only_string_class
contains_only_string_class(a) # => true
contains_only_string_class(b) # => false
contains_only_string_class(c) # => false
答案 0 :(得分:5)
使用all?
def contains_only_string_class(collection)
collection.all? { |obj| obj.is_a?(String) }
end