Crystal How to check if the block argument is given inside the function

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 13:01:14

问题


Suppose a function defined like this:

def composition(text : String, k : Int32) : Array(String)
  kmers = Array(String).new
  (0 .. text.size - k).each do |i|
    kmers << text[i, k]
    yield text[i, k]
  end
  return kmers
end

How do I check if the block argument is given inside the function? If the block argument is given, kmers will be yielded. If not given, kmers will be returned as an array of strings.


回答1:


Such a check is impossible, because a method accepting a block (using yield anywhere) simply has a different signature. But that also means that you don't need the check, just make 2 methods like this:

# if you want to be explicit (makes no difference):
# def composition(text : String, k : Int32, &block)
def composition(text : String, k : Int32)
  (0 .. text.size - k).each do |i|
    yield text[i, k]
  end
end

def composition(text : String, k : Int32) : Array(String)
  kmers = [] of String
  composition(text, k) do |s|
    kmers << s
  end
  return kmers
end


来源:https://stackoverflow.com/questions/39190854/crystal-how-to-check-if-the-block-argument-is-given-inside-the-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!