Class: Array

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

Instance Method Summary collapse

Instance Method Details

#compare(other) ⇒ Object

比较两个数组忽略排序的情况下是否相等



75
76
77
# File 'lib/rails_extend/core/array.rb', line 75

def compare(other)
  (self - other).empty? && (other - self).empty?
end

#ljust!(n, x) ⇒ Object

arr = [1, 2, 3]

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


8
9
10
11
# File 'lib/rails_extend/core/array.rb', line 8

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

#mjust!(n, x) ⇒ Object

arr = [1, 2, 3]

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


26
27
28
29
# File 'lib/rails_extend/core/array.rb', line 26

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 left;

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


17
18
19
20
# File 'lib/rails_extend/core/array.rb', line 17

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

#to_array_hObject

raw_data = [

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

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



58
59
60
# File 'lib/rails_extend/core/array.rb', line 58

def to_array_h
  self.map { |x, y| { x => y } }
end

#to_combine_hObject

combine the same key hash like array

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


41
42
43
44
45
46
47
48
# File 'lib/rails_extend/core/array.rb', line 41

def to_combine_h
  self.inject({}) do |memo, obj|
    memo.merge(obj) do |_, old_val, new_val|
      v = (Array(old_val) + Array(new_val)).uniq
      v.size > 1 ? v : v[0]
    end
  end
end

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

2D array to csv file

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


68
69
70
71
72
# File 'lib/rails_extend/core/array.rb', line 68

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