我知道我可以通过以下代码使其工作,但是阅读和输入非常痛苦:
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