def hoge(a,b) c = a + b ... end
class Array def randomize! #もとのオブジェクトを置き換える srand #乱数の初期化 result = collect { slice!(rand length) } #配列の大きさの範囲で乱数を発生させて #無作為に取り出していく replace result #オブジェクトを置き換える end def randomize #もとのオブジェクトはそのまま arr=self.dup #配列の複製を作成 arr.randomize! arr end end array = [1,2,3,4,5] p array.randomize p array p array.randomize! p array
[1, 2, 4, 5, 3] [1, 2, 3, 4, 5] [4, 5, 1, 2, 3] [4, 5, 1, 2, 3]
class Array def only result = Array.new n = 0 #繰り返し回数 while self.size > n #配列の要素数と繰り返し回数の比較 a = self.dup #元の配列を保存するために、複製を作成 b = a.slice!(n) #「ある地点」の集合 a.flatten!.uniq! #全体から「ある地点」を除いた集合を平滑化+重複除去 result << b-a #「ある地点」だけに含まれる要素を抽出 n += 1 end return result end end array = [[1,2],[2,3],[4,5],[5,6,7]] p array.only
[[1], [3], [4], [6, 7]]
class Array def to_r(name) result = "" result = name + ' <- c(' + self.join(',') + ')' end end a = [1,2,3] p a.to_r("x")
x <- c(1,2,3)