情報学部 | 菅沼ホーム | 目次 | 索引 |
p [1, 2, 3].all? { |v| v > 0 } # => true
p [-1, 2, -3].any? { |v| v > 0 } # => true
p [-1, 2, -3].collect { |v| v > 0 } # => [false, true, false] p [-1, 2, -3].collect # => [-1, 2, -3]
class Test def message p "Not Found" end end obj = Test.new no = obj.method("message") p [-10, 20, -30].find(no) { |v| v > 0 } p [-10, -20, -30].find(no) { |v| v > 0 }
20 "Not Found" nil
p [-10, 20, -30].find_all { |v| v < 0 } # => [-10, -30]
p ["abc", "efg", "xab"].grep(/a./) # => ["abc", "xab"] p [3, 9, 15].grep(1..10) # => [3, 9]
p [1,2,3,4,5].inject(0) { |result, item| result + item } # => 15
p [5, 4, 3, 2, 1].max # => 5 p [5, 4, 3, 2, 1].max { |a, b| -a <=> -b } # => 1
p [5, 4, 3, 2, 1].min # => 1 >p [5, 4, 3, 2, 1].min { |a, b| -a <=> -b } # => 5
p [1, 2, 3, 4, 5].partition { |a| a % 2 == 0 } # => [[2, 4], [1, 3, 5]]
p [1, 2, 3, 4, 5].reject { |a| a % 2 == 0 } # => [1, 3, 5]
class Integer def count $n += 1 return self end end p [2, 1, 5, 3, 4].sort p [2, 1, 5, 3, 4].sort { |a, b| a <=> b } p [2, 1, 5, 3, 4].sort { |a, b| -a <=> -b } p [2, 1, 5, 3, 4].sort { |a, b| (a > b) ? 1 : -1 } p [2, 1, 5, 3, 4].sort { |a, b| (a < b) ? 1 : -1 } $n = 0 p [5, 4, 3, 2, 1].sort { |a, b| a.count() <=> b.count() } printf " $n = %d\n", $n $n = 0 p [5, 4, 3, 2, 1].sort_by { |a| a.count() } printf " $n = %d\n", $n
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [1, 2, 3, 4, 5] $n = 12 [1, 2, 3, 4, 5] $n = 5
p (1..5).to_a # => [1, 2, 3, 4, 5]
p [1, 2].zip( [4, 5, 6], [7, 8, 9] ) # => [[1, 4, 7], [2, 5, 8]] p (1..3).zip( [4, 5], [7, 8, 9] ) # => [[1, 4, 7], [2, 5, 8], [3, nil, 9]]
情報学部 | 菅沼ホーム | 目次 | 索引 |