How to store ruby code blocks

11,765

There are many ways to do this in Ruby, one of which is to use a Proc:

foo = Proc.new do |test|
  puts test
end

3.upto(8) { foo.call("hello world") }

Read more about Procs:

Update, the above method could be rewritten as follows:

# using lower-case **proc** syntax, all on one line
foo = proc { |test| puts test }
3.upto(8) { foo.call("hello world") }

# using lambda, just switch the method name from proc to lambda
bar = lambda { |test| puts test }
3.upto(8) { bar.call("hello world") } 

They're basically very similar methods, with subtle differences.

And finally, there are probably more elegant ways to do what I've outlined, be good to hear from anyone with a better way. Hope this helps.

Share:
11,765

Related videos on Youtube

sawa
Author by

sawa

I have published the following two Ruby gems: dom: You can describe HTML/XML DOM structures in Ruby language seamlessly with other parts of Ruby code. Node embedding is described as method chaining, which avoids unnecessary nesting, and confirms to the Rubyistic coding style. manager: Manager generates a user's manual and a developer's chart simultaneously from a single spec file that contains both kinds of information. More precisely, it is a document generator, source code annotation extracter, source code analyzer, class diagram generator, unit test framework, benchmark measurer for alternative implementations of a feature, all in one. Comments and contributions are welcome. I am preparing a web service that is coming out soon.

Updated on June 17, 2022

Comments

  • sawa
    sawa almost 2 years

    I want to store a "code block" in a variable to be reused, something like:

    block = do
    |test| puts test
    end
    
    3.upto(8) block
    

    Can someone show me what am I doing so obviously wrong? (Or if it's just impossible)

  • Admin
    Admin over 11 years
    Thanks a lot. For the link even more. Can you be so kind as to include a mention of lambdas as well? For historical purpose.
  • stephenmurdoch
    stephenmurdoch over 11 years
    @Shingetsu, I added and update with lambda, as well as a slightly simplified version of the proc approach too
  • Linuxios
    Linuxios over 11 years
    @Shingetsu: Lambdas aren't historical. You should almost always use them instead of Procs. They are much more fully featured and are the standard.
  • Admin
    Admin over 11 years
    @Linuxios by historical I mean "people who will later come see the post". I read the page and saw that lambdas make more sense.
  • Linuxios
    Linuxios over 11 years
    @Shingetsu: Oh! Sorry about that. We all misinterpret sometimes.