5

How can you pass a function by name in Ruby? (I've only been using Ruby for a few hours, so I'm still figuring things out.)

nums = [1, 2, 3, 4]

# This works, but is more verbose than I'd like    
nums.each do |i|
  puts i
end

# In JS, I could just do something like:
# nums.forEach(console.log)

# In F#, it would be something like:
# List.iter nums (printf "%A")

# In Ruby, I wish I could do something like:
nums.each puts

Can it be done similarly concisely in Ruby? Can I just reference the function by name instead of using a block?

People voting to close: Can you explain why this isn't a real question?

1

3 Answers 3

6

You can do the following:

nums = [1, 2, 3, 4]
nums.each(&method(:puts))

This article has a good explanation of the differences between procs, blocks, and lambdas in Ruby.

Sign up to request clarification or add additional context in comments.

1 Comment

It's also possible to specify an instance method, e.g. nums.each(&$stderr.method(:puts))
3

Can I just reference the function by name instead of wrapping it in a block?

You aren't 'wrapping' it -- the block is the function.

If brevity is a concern, you can use brackets instead of do..end:

nums.each {|i| puts i}

Comments

0

Not out-of-the-box, although you can use method:

def invoke(enum, meth)
  enum.each { |e| method(meth).call(e) }
end

I prefer it wrapped up into a monkeypatched Enumerable.

There are other ways to go about this, too; this is kind of brute-force.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.