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

Friday, November 11, 2022

[FIXED] How to declare a block argument with one or two arguments in crystal

 November 11, 2022     crystal-lang, proc     No comments   

Issue

I want to be able accept a block argument, which takes one or two Int arguments

This code does not work, but expresses my intent.
def initialize(*input, &block : (Int32 | (Int32, Int32)) -> Int32) @input = input @calc = block end

This works for a block with one Int argument. How do I make it work with one or two Int arguments?


Solution

Taking a block parameter is optional in Crystal. So just declare the the block with the maximum number of arguments and decide on the call side how many of those you're going to take:

def foo(&block : (Int32, Int32) -> Int32)
  block.call(1, 2)
end

foo {|a, b| a + b } # => 3
foo {|a| a } # => 1
foo { 5 } # => 5


Answered By - Jonne Haß
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • 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