【问题标题】:While Loops in Ruby and Converting to a FunctionRuby 中的 While 循环和转换为函数
【发布时间】:2012-04-07 12:35:41
【问题描述】:

我在 Chapter 33 上 Learn Ruby the Hard Way。

额外学分练习 1 询问:

将此 while 循环转换为您可以调用的函数,并替换 6 在带有变量的测试(i

代码:

i = 0
numbers = []

while i < 6
  puts "At the top i is #{i}"
  numbers.push(i)

  i = i + 1
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end

puts "The numbers: "

for num in numbers
  puts num
end

我的尝试:

i = 0
numbers = []

def loops
while i < 6
  puts "At the top i is #{i}"
  numbers.push(i)

  i = i + 1
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end
 end

 loops
 puts "The numbers: "

for num in numbers
  puts num
end

如您所见,我试图将块变成一个函数,但还没有将 6 变成一个变量。

错误:

ex33.rb:5:in `loops': undefined local variable or method `i' for main:Object (Na
meError)
        from ex33.rb:15:in `<main>'
    from ex33.rb:15:in `<main>'

我做错了什么?

编辑:好的,改进了一点。现在 numbers 变量超出了范围...

def loops (i, second_number)
numbers = []
while i < second_number
  puts "At the top i is #{i}"
    i = i + 1
  numbers.push(i)
  puts "Numbers now: #{numbers}"
  puts "At the bottom i is #{i}"
end
 end

loops(0,6)
puts "The numbers: "

for num in numbers
  puts num
end

【问题讨论】:

    标签: ruby function loops while-loop learn-ruby-the-hard-way


    【解决方案1】:

    正如@steenslag 所说,i 超出了loops 的范围。我不建议改用@i,因为i 仅供loops 使用。

    您的函数是一个可用于生成数字数组的实用程序。该函数使用i 来计算它有多远(但函数的调用者并不关心这个,它只想要得到的numbers)。该函数还需要返回numbers,因此也将其移入loops

    def loops
      i = 0
      numbers = []
    
      while i < 6
        puts "At the top i is #{i}"
        numbers.push(i)
    
        i = i + 1
        puts "Numbers now: #{numbers}"
        puts "At the bottom i is #{i}"
      end
    end
    

    您现在必须考虑loops 的调用者无法再看到numbers 的事实。祝你学习顺利。

    【讨论】:

    • 我刚刚想出了一个带有参数的函数,它也用变量替换了 6,我用代码编辑了 OP。但是,正如您所说,现在“数字”已经看不见了……
    【解决方案2】:

    当您说def 时,i 超出范围。该方法无法“看到”它。改用@i(@ 为变量提供了更大的“可见性”),或者将i=6 移到方法中,或者弄清楚如何在方法中使用参数。

    【讨论】:

      【解决方案3】:

      我可能误读了“转换 while 循环”,但我的解决方案是:

      def loop(x, y)
      
         i = 0
         numbers = []
      
         while i < y
            puts "At the top i is #{i}"
            numbers.push(i)
      
            i += 1
            puts "Numbers now: ", numbers
            puts "At the bottom i is #{i}"
         end
      
         puts "The numbers: "
      
      # remember you can write this 2 other ways?
      numbers.each {|num| puts num }
      
      end
      
      loop(1, 6)
      

      【讨论】:

        猜你喜欢
        • 2012-06-25
        • 2017-02-20
        • 2018-03-15
        • 2015-02-16
        • 1970-01-01
        • 2018-11-21
        • 1970-01-01
        • 1970-01-01
        • 2011-11-08
        相关资源
        最近更新 更多