Ruby-on-rails 如何在rails中创建对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6922768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:41:42  来源:igfitidea点击:

How to create object array in rails?

ruby-on-railsrubyarrays

提问by Coder

I need to know how to create object array in rails and how to add elements in to that.

我需要知道如何在 rails 中创建对象数组以及如何向其中添加元素。

I'm new to ruby on rails and this could be some sort of silly question but I can't find exact answer for that. So can please give some expert ideas about this

我是 ruby​​ on rails 的新手,这可能是一些愚蠢的问题,但我找不到确切的答案。所以可以请给一些专家的意见

回答by Daniel Lyons

All you need is an array:

你只需要一个数组:

objArray = []
# or, if you want to be verbose
objArray = Array.new

To push, pushor use <<:

推送push或使用<<

objArray.push 17
>>> [17]

objArray << 4
>>> [17, 4]

You can use any object you like, it doesn't have to be of a particular type.

您可以使用任何您喜欢的对象,它不必是特定类型的。

回答by edgerunner

Since everything is an object in Ruby (including numbers and strings) any array you create is an object array that has no limits on the types of objects it can hold. There are no arrays of integers, or arrays of widgetsin Ruby. Arrays are just arrays.

由于在 Ruby 中一切都是对象(包括数字和字符串),因此您创建的任何数组都是一个对象数组,它可以容纳的对象类型没有限制。Ruby中没有整数数组小部件数组。数组只是数组。

my_array = [24, :a_symbol, 'a string', Object.new, [1,2,3]]

As you can see, an array can contain anything, even another array.

如您所见,数组可以包含任何内容,甚至是另一个数组。

回答by mnishiguchi

Depending on the situation, I like this construct to initialize an array.

根据情况,我喜欢这个构造来初始化一个数组。

# Create a new array of 10 new objects
Array.new(10) { Object.new }
#=> [#<Object:0x007fd2709e9310>, #<Object:0x007fd2709e92e8>, #<Object:0x007fd2709e92c0>, #<Object:0x007fd2709e9298>, #<Object:0x007fd2709e9270>, #<Object:0x007fd2709e9248>, #<Object:0x007fd2709e9220>, #<Object:0x007fd2709e91f8>, #<Object:0x007fd2709e91d0>, #<Object:0x007fd2709e91a8>]

回答by Kapitula Alexey

Also if you need to create array of words next construction could be used to avoid usage of quotes:

此外,如果您需要创建单词数组,则可以使用下一个构造来避免使用引号:

array = %w[first second third]

or

或者

array = %w(first second third)