lib/open_classes/array.rb in tbpgr_utils-0.0.13 vs lib/open_classes/array.rb in tbpgr_utils-0.0.14
- old
+ new
@@ -1,6 +1,7 @@
# encoding: utf-8
+require 'open_classes/object'
# Array
class Array
# Arrays loop together.
#
@@ -10,15 +11,11 @@
# print "#{first}:#{second}\n" # => output one:1, two:2, three:3
# end
def together
if_not_contain_array_rails_type_error
first.each_with_index do |i_v, i|
- eval_each = []
- each_with_index do |j_v, j|
- eval_each << "self[#{j}][#{i}]"
- end
- eval_each_str = eval_each.join(',')
+ eval_each_str = get_args_str_for_together i
instance_eval "yield(#{eval_each_str})"
end
end
# Arrays loop together with index.
@@ -29,21 +26,73 @@
# print "#{index.to_s}:#{first}:#{second}\n" # => output 0:one:1, 1:two:2, 2:three:3
# end
def together_with_index
if_not_contain_array_rails_type_error
first.each_with_index do |i_v, i|
- eval_each = []
- each_with_index do |j_v, j|
- eval_each << "self[#{j}][#{i}]"
- end
- eval_each << i
- eval_each_str = eval_each.join(',')
+ eval_each_str = get_args_str_for_together i, true
instance_eval "yield(#{eval_each_str})"
end
end
+ # Arrays together map.
+ #
+ # together_map has aliases [:tmap, :together_collect, :tcollect]
+ #
+ # if you want to single Array return
+ # alpha = %w{one two three}
+ # numbers = %w{1 2 3}
+ # print [alpha, numbers].together_map do |first, second|
+ # "#{first}:#{second}\n"
+ # end # => output one:1, two:2, three:3
+ #
+ # if you want to multi Array return
+ # alpha = %w{one two three}
+ # numbers = %w{1 2 3}
+ # print [alpha, numbers].together_map do |first, second|
+ # ["#{first}:#{second}", "#{second}:#{first}"]
+ # end # => output [['1:one', '2:two', '3:three'], ['one:1', 'two:2', 'three:3']]
+ def together_map
+ if_not_contain_array_rails_type_error
+ ret = []
+ first.each_with_index do |i_v, i|
+ eval_each_str = get_args_str_for_together i
+ each_ret = instance_eval "yield(#{eval_each_str})"
+ ret = set_together_each_return(ret, each_ret, i)
+ end
+ ret
+ end
+
+ alias_method :together_collect, :together_map
+ alias_method :tmap, :together_map
+ alias_method :tcollect, :together_map
+
private
def if_not_contain_array_rails_type_error
each { |f|fail TypeError, "you have to use [Array1, Array2, ...] | #{f.class} is invalid" unless f.class == Array }
+ end
+
+ def get_args_for_together(i)
+ eval_each = []
+ each_with_index {|j_v, j|eval_each << "self[#{j}][#{i}]"}
+ eval_each
+ end
+
+ def get_args_str_for_together(i, with_index = false)
+ each_eval = with_index ? get_args_for_together(i) << i : get_args_for_together(i)
+ each_eval.join(',')
+ end
+
+ def set_together_each_return(ret, each_ret, index)
+ if together_return_multi?(each_ret)
+ self.size.times {|i|ret << []} if index == 0
+ (0..(self.size - 1)).each {|i|ret[i] << each_ret[i]}
+ else
+ ret << each_ret
+ end
+ ret
+ end
+
+ def together_return_multi?(list)
+ (list.class == Array && list.size == self.size).to_bool
end
end