2012-11-09 75 views
0

的數組我有以下數組不可變的方法來改變屬性的對象

Bot = Struct.new(:name, :age) 

bots = %w(foo bar baz).map do |name| 
    Bot.new(name, rand(10)) 
end 

p bots 
[ #<struct Bot name="foo", age=3>, 
    #<struct Bot name="bar", age=8>, 
    #<struct Bot name="baz", age=0> ] 

我想從bots,其中age屬性轉換to_s得到一個新的數組,但我不想改變數組中的真實物體bots。 我該怎麼做?

回答

1

這將保留機器人:

new_bots = bots.map {|bot| Bot.new(bot.name, bot.age.to_s) } 

這將保存機器人:

new_bots = bots.map! {|bot| Bot.new(bot.name, bot.age.to_s) } 

地圖!修改它被調用的對象,就像大多數以!結尾的方法一樣。這是地圖的可變版本。

地圖不會修改被調用的對象的內容。大多數數組方法是不可變的,除了那些以數組結尾的方法! (但只是一個慣例,所以要小心)。

1
Bot = Struct.new(:name, :age) 

bots = %w(foo bar baz).map do |name| 
    Bot.new(name, rand(10)) 
end 
#=> [#<struct Bot name="foo", age=4>, 
# #<struct Bot name="bar", age=5>, 
# #<struct Bot name="baz", age=8>] 

bots.map { |bot| Bot.new(bot.name, bot.age.to_s)} 
#=> [#<struct Bot name="foo", age="4">, 
# #<struct Bot name="bar", age="5">, 
# #<struct Bot name="baz", age="8">] 
相關問題