Ruby:修改Struct中的哈希元素?

时间:2012-05-04 06:46:23

标签: ruby

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

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

1 个答案:

答案 0 :(得分: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