【问题标题】:Trying to store input as a Hashmap in ruby尝试将输入存储为红宝石中的哈希图
【发布时间】:2017-11-16 17:41:54
【问题描述】:

我正在尝试使用 Ruby 将用户输入存储为哈希图。期望的结果是(假设用户输入,5,5,N)

位置 = {"x" => 5; "y" => 5; D => "N"}

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

end

【问题讨论】:

  • 你没有问问题。

标签: ruby-on-rails ruby


【解决方案1】:

不要重新构建哈希,您已经构建了它。做吧:

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" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-17
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多