【问题标题】:Send in a number and return an array in Ruby [closed]在Ruby中发送一个数字并返回一个数组[关闭]
【发布时间】:2011-12-20 23:47:45
【问题描述】:

我需要以下方面的帮助:

  1. 在方法中根据输入参数创建一个新数组
  2. 从该方法返回一个数组
  3. 最优雅的输出数组的内容?


mycontroller.rb

def test(num)
  #take the number and create a new array and return the array with the numbers.
  #example input: 5
  #output: array with 5 indexes and values of [1,2,3,4,5]
end

# output the contents of the array
i = 0
while i < 5
  puts test(i)
end

谢谢!

【问题讨论】:

  • 如果这不是问题,那么你需要回到小学去了解“问题”的定义是什么。这不是家庭作业。我正在学习 Ruby,需要帮助来理解它。
  • 然后问一个问题。您有一个不构成问题的三个不相关要求的列表,而 Stack Overflow 绝对不是为您编写代码。

标签: ruby-on-rails ruby


【解决方案1】:

您可以为此使用ruby ranges

list = (1..num).to_a

要打印数组,请使用inspect 方法,即

puts list.inspect

【讨论】:

  • +1 为琐碎任务的琐碎解决方案。
  • puts foo.inspectp foo 一样不是吗?
  • @JörgWMittag,它是一样的。如果用户想要漂亮的字符串进行进一步修改,foo.inspect 很方便。例如:puts "The list is content is #{foo.inspect}"
【解决方案2】:

这样的?

def test(num)
  1.upto(num).to_a
end

对于输出:

puts test(5).join(', ') # outputs "1, 2, 3, 4, 5"

【讨论】:

    【解决方案3】:

    这个定义有很多可能的方法。

    我总是更喜欢告诉初学者编写他们可以像书一样阅读的代码,使用该语言最容易理解的方法和类,在这种情况下我会推荐:

    def num_array(num)
        array = Array.new
        count = 1
        num.times {
          array << count
          count =  count + 1
        }
        return array
    end
    

    并检查它:

    i = 1
    while i <= 5
      new_array = Array.new
      new_array = num_array(i)
      puts new_array.inspect
      i = i + 1
    end
    

    是的,我提供的代码示例可以简化很多,但是任何至少阅读过 Ruby 教程的初学者都应该能够理解和复制上述代码,一旦他们熟悉了他们可以开始制作的语言更改为更复杂的语法。

    就像将i = i + 1 交换为i += 1

    或将以上所有内容交换为list = (1..num).to_a

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 2014-09-16
      • 2017-08-15
      • 2017-04-03
      • 2021-01-21
      • 2021-11-20
      • 2014-12-12
      • 2022-01-13
      相关资源
      最近更新 更多