整理我的阵列红宝石 [英] Organize my array ruby

查看:79
本文介绍了整理我的阵列红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图尽可能地优化我的代码,但我已经陷入僵局。

im trying to optimize my code as much as possible and i've reached a dead end.

我的代码如下:

class Person
  attr_accessor :age
  def initialize(age)
    @age = age
  end
end

people = [Person.new(10), Person.new(20), Person.new(30)]

newperson1 = [Person.new(10)]
newperson2 = [Person.new(20)]
newperson3 = [Person.new(30)]

有没有一种方法可以让我获得ruby来自动从people数组中提取数据并将其命名为newnew1等。

Is there a way where i can get ruby to automatically pull data out from the people array and name them as following newperson1 and so on..

最诚挚的问候

推荐答案

那绝对是代码的味道。您应该将它们称为 [people [0]] [people [1]] ,...。

That is definitely a code smell. You should refer to them as [people[0]], [people[1]], ... .

但是如果您坚持要这样做,并且可以等到12月25日(Ruby 2.1),那么您可以这样做:

But if you insist on doing so, and if you can wait until December 25 (Ruby 2.1), then you can do:

people.each.with_index(1) do |person, i|
  binding.local_variable_set("newperson#{i}", [person])
end

这篇关于整理我的阵列红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆