Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_com/core/array.rb

Direct Known Subclasses

Settings

Instance Method Summary collapse

Instance Method Details

#ljust!(n, x) ⇒ Object

arr = [1, 2, 3]

arr.ljust! 5, nil
# => [nil, nil, 1, 2, 3]


16
17
18
19
# File 'lib/rails_com/core/array.rb', line 16

def ljust!(n, x)
  return self if n < length
  fill(x, length...n)
end

#mjust!(n, x) ⇒ Object

arr = [1, 2, 3]

arr.mjust!(5, nil)
# => [1, 2, nil, nil, 3]


25
26
27
28
# File 'lib/rails_com/core/array.rb', line 25

def mjust!(n, x)
  return self if n < length
  insert (length / 2.0).ceil, *Array.new(n - length, x)
end

#rjust!(n, x) ⇒ Object

fill an array with the given elements right;

arr = [1, 2, 3]
arr.rjust! 5, nil
# => [1, 2, 3, nil, nil]


7
8
9
10
# File 'lib/rails_com/core/array.rb', line 7

def rjust!(n, x)
  return self if n < length
  insert(0, *Array.new([0, n-length].max, x))
end

#to_combined_hObject

raw_data = [

[:a, 1],
[:a, 2],
[:b, 2]

] raw_data.to_combined_h #=> { a: [1, 2], b: 2 } todo nested array bug



54
55
56
57
58
# File 'lib/rails_com/core/array.rb', line 54

def to_combined_h
  hash = {}
  self.each { |x, y| hash[x] = hash[x] ? Array(hash[x]) << y : y  }
  hash
end

#to_combined_hashObject

combine the same key hash like array

raw_data = [
  { a: 1 },
  { a: 2 },
  { b: 2 }
]
raw_data.to_combined_hash
#=> { a: [1, 2], b: 2 }


39
40
41
42
43
# File 'lib/rails_com/core/array.rb', line 39

def to_combined_hash
  self.reduce({}) do |memo, index|
    memo.merge(index) { |_, value, default| [value, default] }
  end
end

#to_csv_file(file = 'export.csv') ⇒ Object

2D array to csv file

data = [
  [1, 2],
  [3, 4]
]
data.to_csv_file


66
67
68
69
70
# File 'lib/rails_com/core/array.rb', line 66

def to_csv_file(file = 'export.csv')
  CSV.open(file, 'w') do |csv|
    self.each { |ar| csv << ar }
  end
end