How can I splattify an anonymous object so that I can use the & method on it?

I want to use the idiom &method(:method_name) if more than one object is required for method_name . Can I do this under Ruby 1.9?

For example, if I have

 def move_file(old_filename, new_filename) STDERR.puts "Moving #{old_filename.inspect} to #{new_filename.inspect}" # Implementation for careful moving goes here end old_filenames = ["foo.txt", "bar.txt", "hoge.ja.txt"] new_filenames = ["foo_20110915.txt", "bar_20110915.txt", "hoge_20110915.ja.txt"] 

code

 old_filenames.zip(new_filenames).each(&method(:move_file)) 

works under Ruby 1.8, but not under Ruby 1.9. Under Ruby 1.9, he tries to make move_file(["foo.txt", "foo_20110915.txt"]) instead of move_file("foo.txt", "foo_20110915.txt") .

How can I split it so that it has the correct arity?

Workarounds I know of:

  • Replace def move_file(old_filename, new_filename) with def move_file(*arguments)
  • Replace each(&method(:move_file)) with each{|old_filename, new_filename| move_file(old_filename, new_filename)} each{|old_filename, new_filename| move_file(old_filename, new_filename)}
+4
source share
2 answers

Instead

 each{|old_filename, new_filename| move_file(old_filename, new_filename)} 

you should be able to do

 each{|pair| move_file(*pair)} 

But I do not know how you would remove the option without a block (I needed this a couple of times). I suppose & -shorthand was made to simplify the syntax and should not get too clogged (for example, whether it will be passed to the array as an array or, for example, splatted). :)

+1
source

How can I split it so that it has the correct arity?

I donโ€™t think there is a way to do this, being compatible with both versions of Ruby. What you can do is wrap it in lambda

move_from_to = Proc.new {| * both | move_files (* both)}

The thing - block and proc arity is what was discussed in Ruby 1.9, so there might be a difference in behavior. Also see prc.lambda? here http://www.ruby-doc.org/core/classes/Proc.html for information on what he does with the arch.

This question is also related to what you want to do (manual solution for resplat and unsplat): Arity inconsistency between Hash.each and lambdas

0
source

All Articles