tbpgr / tbpgr_utils

Utility gem
MIT License
1 stars 16 forks source link

Enumerable#kernel_send #4

Open cielavenir opened 9 years ago

cielavenir commented 9 years ago

(1..3).map(&method('Rational'.to_sym)) is enough. If we want to remove to_sym, at least we should rename the name to kernel_send_map.

tbpgr commented 9 years ago

I agree.

Fix Plan

# Enumerable
module Enumerable
  def kernel_send_each(method_name)
    return self unless [Symbol, String].include? method_name.class
    each { |v|send method_name.to_sym, v }
    self
  end

  def kernel_send_map(method_name)
    return self unless [Symbol, String].include? method_name.class
    map { |v|send method_name.to_sym, v }
  end
end

# [*1..3].kernel_send:Rational # => [(1/1), (2/1), (3/1)]
print [*1..3].kernel_send_each(:Rational), "\n" # => return [1,2,3]
print [*1..3].kernel_send_each(:print), "\n" # => print 123, return [1,2,3]

print [*1..3].kernel_send_map(:Rational), "\n" # => [(1/1), (2/1), (3/1)]
print [*1..3].kernel_send_map(:print), "\n" # => print 123, return [nil,nil,nil]
cielavenir commented 9 years ago

I think this code is now all right.

tbpgr commented 9 years ago

Thanks. I'll fix it, later.

cielavenir commented 9 years ago

Well, I have found another thing.

[Symbol, String].include? method_name.class should be [Symbol, String].any?(&method_name.method(:is_a?)). How do you think? Well, calling is_a? for multiple times might not be good though...

cielavenir commented 9 years ago

Or, even method_name.respond_to?(:to_sym) (might breach the semantics though)