Ruby - 可变变量集等于自定义类的对象将自定义类传递给变量吗?

时间:2014-04-10 05:11:45

标签: ruby arrays class object inheritance

class New_Class
   def initialize
      @array = ['1A','2A','1B','2C']
   end
   def remove_letters
      @array.map do |rmv|
         rmv.sub /([0-9])([A-Z])/, '\1'
      end
   end
   def show_array
      @array.each do |element|
         puts element
      end
   end
end

array = New_Class.new
new_array = array.remove_letters
puts new_array.class #=> Array
new_array.each do |element|
   puts element   #=>1,2,1,2
end
array.show_array   #=>1A,2A,1B,2C
new_array.show_array   #=>Undefined method error since it's an object of type Array not New_Class

如何使new_array成为New_Class类型的对象而不是Array? 这不起作用:

new_array = New_Class.new
new_array = array.remove_letters 

仍然说new_array是Array类型。

我玩克隆和复制,但也无法以这种方式工作。谢谢!

1 个答案:

答案 0 :(得分:0)

您的remove_letters方法返回一个数组,然后将其分配给new_array。如果您希望new_array成为New_Class的另一个实例,则需要从NewClass方法返回另一个remove_letters实例,而不是数组:

def initialize(values = ['1A','2A','1B','2C']) 
  @array = values
end

def remove_letters
  New_Class.new(@array.map { |rmv| rmv.sub(/([0-9])([A-Z])/, '\1') })      
end

上面,我修改initialize以将您的数组用作默认值,如果初始数组值未传递给New_Class.new,则默认使用['1A','2A','1B','2C']