加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:No Block Given错误

发布时间:2020-12-16 19:24:43 所属栏目:百科 来源:网络整理
导读:尝试将字符串传递给is_tut时,我一直收到“no block given”错误?方法.我是 Ruby的新手,不知道我做错了什么.任何和所有的帮助将不胜感激. class Tut@@consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]
尝试将字符串传递给is_tut时,我一直收到“no block given”错误?方法.我是 Ruby的新手,不知道我做错了什么.任何和所有的帮助将不胜感激.
class Tut
@@consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]

  def is_tut? string
    if string =~ /^(([b-df-hj-np-z]ut)|([aeious])|[[:punct:]])+$/i
      yield
    else
      false
    end
  end

  def self.to_tut string 
        string.each_char do |c|
            c += "ut" if @@consonants.find { |i| i == c.downcase }
            yield c
        end
    end

    def self.to_english string
        array = string.split //
        array.each do |c|
            if @@consonants.find { |i| i == c.downcase }
                array.shift
                array.shift
            end
            yield c
        end
    end


end

#Tut.to_tut( "Wow! Look at this get converted to Tut!" ) { |c| print c }
# should output : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!

puts
puts

tut = Tut.to_tut( "Wow! Look at this get converted to Tut!" )
puts "from return: #{tut}"

puts

#Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" ) { |c| print c }
# should outout : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!
puts
puts

#tut = Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" )
#puts "from return: #{tut}"

puts

#tut_string = ""
#Tut.to_tut( "I'm in tut but I want to be in english." ) { |c| tut_string += c }
#puts tut_string
# should output : I'mut inut tututut bututut I wutanuttut tuto bute inut enutgutlutisuthut.

puts

#Tut.to_english( tut_string ) { |c| print c }
# should output : I'm in tut but I want to be in english.

解决方法

如果在方法定义中有收益,则意味着在使用时必须强制传递一个块(除非包含它的部分不是根据条件执行等). (您可能已经知道了,但是如果您不知道:一个块被描述为{…}或者…结束)并且yield将引用该块.

如果你想要一个块可选,那么一种方法是将&变量名前的符号.

def method(argument,&block_argument)
   if block_argument # block is given
      block_argument.call(argument_for_block) # use call to execute the block
   else # the value of block_argument becomes nil if you didn't give a block
      # block was not given
   end
end

这将允许可选块.或者,正如Squeegy所建议的,

def method(argument)
   if block_given? # block is given
      yield(argument_for_block) # no need to use call to execute the block
   else 
      # block was not given
   end
end

也会工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读