PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 10, 2022

[FIXED] How to store ruby code blocks

 November 10, 2022     block, proc, ruby     No comments   

Issue

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)


Solution

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:

  • http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas
  • http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/

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.



Answered By - stephenmurdoch
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing