Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Instance Variables from Objects in an Array

Tags:

ruby

I'm new to Ruby and I'm just having a play around with ideas and what I would like to do is remove the @continent data from the country_array I have created. Done a good number of searches and can find quite a bit of info on removing elements in their entirety but can't find how to specifically remove @continent data. Please keep any answers fairly simple as I'm new, however any help much appreciated.

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">]
like image 502
Tom Avatar asked Aug 24 '11 14:08

Tom


2 Answers

You can use remove_instance_variable. However, since it's a private method, you'll need to reopen your class and add a new method to do this:

class World
  def remove_country
    remove_instance_variable(:@country)
  end
end

Then you can do this:

country_array.each { |item| item.remove_country }
# => [#<World:0x7f5e41e07d00 @country="Spain">, 
      #<World:0x7f5e41e01450 @country="India">, 
      #<World:0x7f5e41df5100 @country="Argentina">, 
      #<World:0x7f5e41dedd10 @country="Japan">] 
like image 136
Dylan Markow Avatar answered Oct 26 '22 14:10

Dylan Markow


The following example will set the @continent to nil for the first World object in your array:

country_array[0].continent = nil

irb(main):035:0> country_array[0]
=> #<World:0xb7dd5e84 @continent=nil, @country="Spain">

But it doesn't really remove the continent variable since it's part of your World object.

Have you worked much with object-oriented programming? Is your World example from a book or tutorial somewhere? I would suggest some changes to how your World is structured. A World could have an array of Continent's, and each Continent could have an array of Country's.

Names have meaning and variable names should reflect what they truly are. The country_array variable could be renamed to world_array since it is an array of World objects.

like image 22
dustmachine Avatar answered Oct 26 '22 13:10

dustmachine