Ruby/Array/to String

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Convert array to a set: it removes duplicate elements for you

require "set"
survey_results = [1, 2, 7, 1, 1, 5, 2, 5, 1]
p distinct_answers = survey_results.to_set
# => #<Set: {5, 1, 7, 2}>



Inject a two-dimensional array to set

require "set"
games = [["Alice", "Bob"], ["Carol", "Ted"],
         ["Alice", "Mallory"], ["Ted", "Bob"]]
p players = games.inject(Set.new) { |set, game| game.each { |p| set << p }; set }
# => #<Set: {"Alice", "Mallory", "Ted", "Carol", "Bob"}>
p players << "Ted"
# => #<Set: {"Alice", "Mallory", "Ted", "Carol", "Bob"}>