首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ruby中循环并转换为函数

在Ruby中循环并转换为函数
EN

Stack Overflow用户
提问于 2012-03-22 21:36:14
回答 3查看 1.9K关注 0票数 2

我在第33章学习红宝石的艰难之路。

额外学分练习1要求:

将这个while循环转换为您可以调用的函数,并用变量替换测试中的6 (i < 6)。

守则:

代码语言:javascript
复制
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

我的尝试:

代码语言:javascript
复制
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成为一个变量。

错误:

代码语言:javascript
复制
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>'

我做错了什么?

编辑:好的,稍微改进一下。数字变量超出了范围..。

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-22 21:58:33

正如@steenslag所说,i超出了loops的范围。我不建议切换到使用@i,因为i只被loops使用。

您的函数是一个实用程序,可以用来生成一个数字数组。这个函数使用i来计算出它到底有多远(但是函数的调用方并不关心这个问题,它只需要得到结果的numbers)。函数还需要返回numbers,所以也要将它移到loops中。

代码语言:javascript
复制
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。祝你学习顺利。

票数 0
EN

Stack Overflow用户

发布于 2012-03-22 21:46:43

当你说def时,i就超出了范围。这个方法不能“看到”它。代之以使用@i (@使变量具有更大的“可见性”),或将i=6移动到方法中,或研究如何使用方法参数。

票数 0
EN

Stack Overflow用户

发布于 2016-02-12 13:58:07

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

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9830928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档