0

我知道我可以通过以下代码使其工作,但是阅读和输入非常痛苦:

def changer   
  @animals[ "birds" ][2] = "Raven"
  @animals[ "birds" ][3] = "Spoonbill"
  display
end

def display
  puts "...#{@animals[ "birds" ][2]}, #{@animals[ "birds" ][3]}."
end

@animals = Hash.new
@animals[ "birds" ] = [ "Cardinal", "Bluejay", "Ostrich", "Flamingo" ]
puts @animals[ "birds" ][2] # => Ostrich
puts @animals[ "birds" ][3] # => Flamingo
changer

我怎样才能让它看起来更像这样?(不幸的是,我也不能将变量作为参数传递。)

Animals = Struct.new(:red, :blue, :black, :pink )

def changer
  @b.black = "Raven"
  @b.pink = "Spoonbill"
  display
end

def display
  puts "New birds are #{@b.red}, #{@b.blue}, #{@b.black}, #{@b.pink}."
  # definitely unchanged still... => New birds are Cardinal, Bluejay, Ostrich, Flamingo.
end

@animals = Hash.new
@animals[ "birds" ] = [ "Cardinal", "Bluejay", "Ostrich", "Flamingo" ]
@b = Animals.new(*@animals[ "birds" ] )
puts @b.black # => Ostrich
puts @b.pink  # => Flamingo
changer

提前感谢您的任何帮助或指示。

编辑:嗯,这是迄今为止我想出的最好的(工作)代码。警告:它不漂亮。

Animals = Struct.new(:red, :blue, :black, :pink )

def changer
  b = Animals.new(*@animals[ "birds" ] )
  b.black = "Raven"
  b.pink = "Spoonbill"
  @animals[ "birds" ][2] = b.black
  @animals[ "birds" ][3] = b.pink
  display
end

def display
  b = Animals.new(*@animals[ "birds" ] )
  puts "New birds are #{b.red}, #{b.blue}, #{b.black}, #{b.pink}."
end

@animals = Hash.new
@animals[ "birds" ] = [ "Cardinal", "Bluejay", "Ostrich", "Flamingo" ]
b = Animals.new(*@animals[ "birds" ] )
puts b.black # => Ostrich
puts b.pink  # => Flamingo
changer
4

1 回答 1

0

问题的原因是您Animal在每个方法中都创建了一个新对象,而不是传递您首先创建的对象。在显示中,基于散列Animal的内容从头开始创建一个新实例。animal['birds']所以它的内容当然不会改变。

可能,您也不是要创建animals为实例变量,而是作为局部变量:只需省略@.

Animals = Struct.new(:red, :blue, :black, :pink )

def changer(animal)
  animal.black = "Raven"
  animal.pink = "Spoonbill"
  display animal
end

def display(animal)
  puts "New birds are #{animal.red}, #{animal.blue}, #{animal.black}, #{animal.pink}."
end

animals = Hash.new
animals[ "birds" ] = [ "Cardinal", "Bluejay", "Ostrich", "Flamingo" ]
b = Animals.new(*animals[ "birds" ] )
puts b.black # => Ostrich
puts b.pink  # => Flamingo
changer b
于 2012-05-04T17:41:19.080 回答