るりまサーチ

最速Rubyリファレンスマニュアル検索!
22件ヒット [1-22件を表示] (0.067秒)

別のキーワード

  1. openssl integer
  2. asn1 integer
  3. _builtin integer
  4. integer upto
  5. integer new

キーワード

検索結果

Enumerable#sort_by -> Enumerator (109.0)

ブロックの評価結果を <=> メソッドで比較することで、self を昇 順にソートします。ソートされた配列を新たに生成して返します。

...][ruby]{
class Array
def sort_by
self.map {|i| [yield(i), i] }.
sort {|a, b| a[0] <=> b[0] }.
map {|i| i[1]}
end
end
//}

Enumerable
#sort と比較して sort_by が優れている点として、
比較条件が複雑な場合の速度が挙げられます。
sort_by を使わ...
...

//emlist[][ruby]{
class Integer
def count
$n += 1
self
end
end

ary = []
1.upto(1000) {|v| ary << rand(v) }

$n = 0
ary.sort {|a,b| a.count <=> b.count }
p $n # => 18200

$n = 0
ary.sort_by {|v| v.count }
p $n # => 1000
//}

Enumerable
#sort_by は安定ではあり...
...できます。

//emlist[][ruby]{
i = 0
ary.sort_by {|v| [v, i += 1] }
//}

※ 比較結果が同じ要素は元の順序通りに並ぶソートを
「安定なソート (stable sort)」と言います。

ブロックを省略した場合は Enumerator を返します。


@see Enumerable#sort...

Enumerable#find_index -> Enumerator (105.0)

条件に一致する最初の要素の位置を返します。

...nil を返します。

//emlist[例][ruby]{
(1..10).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> 34
//}

引数、ブロックのどちらも与えられなかった場合は、
Enumerator のインスタンスを返します。...