Ruby:No Block Given错误

前端之家收集整理的这篇文章主要介绍了Ruby:No Block Given错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试将字符串传递给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)|([aeIoU\s])|[[: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

也会工作.

猜你在找的Ruby相关文章