不要重新构建哈希,您已经构建了它。做吧:
def rover_position()
position = {}
puts "Please input the rovers X position "
position["x"] = gets.chomp
puts "Please input the rovers Y position "
position["y"] = gets.chomp
puts "Please input the rovers Direction (N,E,S,W) "
position["D"] = gets.chomp
position
end
在控制台中,看起来像:
2.3.1 :001 > def rover_position()
2.3.1 :002?> position = {}
2.3.1 :003?> puts "Please input the rovers X position "
2.3.1 :004?> position["x"] = gets.chomp
2.3.1 :005?> puts "Please input the rovers Y position "
2.3.1 :006?> position["y"] = gets.chomp
2.3.1 :007?> puts "Please input the rovers Direction (N,E,S,W) "
2.3.1 :008?> position["D"] = gets.chomp
2.3.1 :009?> position
2.3.1 :010?> end
=> :rover_position
2.3.1 :011 >
2.3.1 :012 > position = rover_position
Please input the rovers X position
5
Please input the rovers Y position
5
Please input the rovers Direction (N,E,S,W)
N
=> {"x"=>"5", "y"=>"5", "D"=>"N"}
2.3.1 :013 > position
=> {"x"=>"5", "y"=>"5", "D"=>"N"}
如果您愿意,可以稍微清理一下,然后执行以下操作:
def rover_position
{
x: "x position",
y: "y position",
D: "Direction (N,E,S,W)"
}.each_with_object({}) do |(key, message), hsh|
puts "Please input the rovers #{message}"
hsh[key] = gets.chomp
end
end
再次,在控制台中:
2.3.1 :001 > def rover_position
2.3.1 :002?> {
2.3.1 :003 > x: "x position",
2.3.1 :004 > y: "y position",
2.3.1 :005 > D: "Direction (N,E,S,W)"
2.3.1 :006?> }.each_with_object({}) do |(key, message), hsh|
2.3.1 :007 > puts "Please input the rovers #{message}"
2.3.1 :008?> hsh[key] = gets.chomp
2.3.1 :009?> end
2.3.1 :010?> end
=> :rover_position
2.3.1 :011 > position = rover_position
Please input the rovers x position
5
Please input the rovers y position
5
Please input the rovers Direction (N,E,S,W)
N
=> {:x=>"5", :y=>"5", :D=>"N"}
2.3.1 :012 > position[:x]
=> "5"
2.3.1 :013 > position[:y]
=> "5"
2.3.1 :014 > position[:D]
=> "N"