加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 从数组中的对象中删除实例变量

发布时间:2020-12-17 04:33:47 所属栏目:百科 来源:网络整理
导读:我是 Ruby的新手,我只是在玩想法,我想要做的是从我创建的country_array中删除@continent数据.完成了大量的搜索,可以找到有关完整删除元素的相关信息,但无法找到如何专门删除@continent数据.请保持任何答案相当简单,因为我是新的,但任何帮助非常感谢. class W
我是 Ruby的新手,我只是在玩想法,我想要做的是从我创建的country_array中删除@continent数据.完成了大量的搜索,可以找到有关完整删除元素的相关信息,但无法找到如何专门删除@continent数据.请保持任何答案相当简单,因为我是新的,但任何帮助非常感谢.
class World
  include Enumerable
  include Comparable

  attr_accessor :continent
  def <=> (sorted)
    @length = other.continent
  end

  def initialize(country,continent)
    @country = country
    @continent = continent
  end 
end

a = World.new("Spain","Europe")
b = World.new("India","Asia")
c = World.new("Argentina","South America")
d = World.new("Japan","Asia")

country_array = [a,b,c,d]

puts country_array.inspect

[#<World:0x100169148 @continent="Europe",@country="Spain">,#<World:0x1001690d0 @continent="Asia",@country="India">,#<World:0x100169058 @continent="South America",@country="Argentina">,#<World:0x100168fe0 @continent="Asia",@country="Japan">]

解决方法

您可以使用remove_instance_variable.但是,由于它是一个私有方法,您需要重新打开您的类并添加一个新方法来执行此操作:
class World
  def remove_country
    remove_instance_variable(:@country)
  end
end

然后你可以这样做:

country_array.each { |item| item.remove_country }
# => [#<World:0x7f5e41e07d00 @country="Spain">,#<World:0x7f5e41e01450 @country="India">,#<World:0x7f5e41df5100 @country="Argentina">,#<World:0x7f5e41dedd10 @country="Japan">]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读