Ruby:No Block Given错误

时间:2011-04-03 00:19:37

标签: ruby

尝试将字符串传递给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.

3 个答案:

答案 0 :(得分:18)

如果您的方法定义中有yield,则表示您在使用时必须强制传递一个块(除非包含它的部分未根据条件等执行)。 (您可能已经知道,但是如果您不知道:一个块被描述为{...}do ... end),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

也可以。

答案 1 :(得分:1)

由于您在yield方法中呼叫to_tut(),因此该行将失败:

tut = Tut.to_tut( "Wow! Look at this get converted to Tut!" )

需要给出一个阻止(正如你在Tut.to_tut()的第一次注释掉的调用中所做的那样),你需要修改你的{ {1}}功能make the code block optional

to_tut()

答案 2 :(得分:0)

yield需要将一个块传递给to_tut

当你这样做时:

Tut.to_tut( "Wow! Look at this get converted to Tut!" ) { |c| print c }

它有效,因为它有块{ |c| print c }

如果没有阻止,则会引发错误。