LoginSignup
3
3

More than 5 years have passed since last update.

配列の中身を真偽で分ける方法

Last updated at Posted at 2016-01-06

タイトルのままなんですが便利なメソッド見つけたのでメモ

パッと思いついた方法はこれ

pry(main)> arr = ["cat", 123, "mouse", 0.99, :dog]
pry(main)> numbers = arr.select { |item| item.kind_of?(Numeric) }
=> [123, 0.99]
pry(main)> non_numbers = arr.reject { |item| numbers.include?(item) }
=> ["cat", "mouse", :dog]

いまいちスマートじゃないのでxorでできるかなと思ったら

pry(main)> non_numbers = arr ^ numbers
NoMethodError: undefined method `^' for ["cat", 123, "mouse", 0.99, :dog]:Array
from (pry):24:in `<main>'

配列はダメみたいです。

で、見つけた解決策がpartition

pry(main)> numbers, non_numbers = arr.partition { |item| item.kind_of?(Numeric) }
=> [[123, 0.99], ["cat", "mouse", :dog]]
pry(main)> numbers
=> [123, 0.99]
pry(main)> non_numbers
=> ["cat", "mouse", :dog]

便利

参考
http://docs.ruby-lang.org/ja/2.2.0/method/Enumerable/i/partition.html
http://ref.xaio.jp/ruby/classes/enumerable/partition(古い情報です)

3
3
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3