Hi,
def map_messages( *args )
args.map{ | message_and_args |
m = Array === message_and_args ? message_and_args : [
message_and_args ]
send *m
}
end
“abcd”.map_messages( [ :[], 1, 2], :size )
end
At least in Ruby 1.8.6 (the version I’ve installed) you dont need to
test if it’s an Array.
puts *[1] # 1
puts *1 # 1
Supposing that 1.9 maintains that behaviour, I propose the following:
class Object
def map_messages(*args)
args.map{ |msg_and_args| send *msg_and_args }
end
def map_messages_with_block(*args)
args.map do |msg|
if !msg.is_a?(Array) || !msg.last.is_a?(Proc)
send(*msg)
else
send(*msg[0…-1], &msg.last)
end
end
end
end
Obvious map_messages_with_block has a performance penalty, that’s why I
kept both.
puts “abcd”.map_messages([:[], 1, 2], :upcase, :downcase).inspect
blk = Proc.new{ |obj| obj.map_messages([:[], 1, 2], :upcase, :downcase)}
puts [“abcd”, “bcde”].map_messages_with_block([:each, blk], [:[],
1]).inspect
Tell me what you think about it.
Pedro.