如何遍历哈希数组以在ruby中找到用户名?

问题描述 投票:-1回答:3

我正在尝试遍历此哈希数组以查找用户搜索的用户名。问题是,无论何时我搜索除第一个值外都不会填充的内容。

 users = [
          { username: "mashrur", password: "password1" },
          { username: "jack", password: "password2" },
          { username: "arya", password: "password3" },
          { username: "jonshow", password: "password4" },
          { username: "heisenberg", password: "password5" }
        ]
puts "Username"
temp_username = gets.chomp
users.each do |user_record|
  if user_record[:username] == temp_username
    puts "Succesfully Logged In"
    break
  else
    puts "Please try again"
    break
  end
end 
arrays ruby loops hash
3个回答
2
投票

if user_record[:username] == temp_username的两个分支都使用break

这意味着您的循环将始终在第一次迭代后结束。

作为建议,您可以尝试通过以下方式重写代码:

users = [
          { username: "mashrur", password: "password1" },
          { username: "jack", password: "password2" },
          { username: "arya", password: "password3" },
          { username: "jonshow", password: "password4" },
          { username: "heisenberg", password: "password5" }
        ]
puts "Username"
temp_username = gets.chomp

user = users.find { |user_record| user_record[:username] == temp_username }

if user
  puts "Succesfully Logged In"
else
  puts "Please try again"
end

1
投票

听起来您想一直要求输入用户名,直到找到已登录的用户;也就是说,直到h[:username]等于为h中的一个哈希users输入的名称。如果是这样,您首先要构建一个循环,该循环显示输入的每个用户名的结果,并提供一种在找到登录用户时退出循环的方法。

loop do
  ...
  <display result for current user entry>
  <break if named user is logged in>
end

请参见Kernel#loop。您首先需要获取用户名。

loop do
  print "Username: "
  name = gets.chomp
  ...
  <display result for current user entry>
  <break if the value of name is logged in>
end

现在我们需要查找是否已登录name的值。

users = [
  { username: "mashrur", password: "password1" },
  { username: "jack", password: "password2" },
  { username: "arya", password: "password3" },
  { username: "jonshow", password: "password4" },
  { username: "heisenberg", password: "password5" }
]

loop do
  print "Username: "
  name = gets.chomp
  found = users.find { |h| h[:username] == name }
  ...
  <display result for current user entry>
  <break if the value of name is logged in>
end

请参见Enumerable#find。如果find包含这样的哈希,则h返回其h[:username] == nametrue的哈希users,否则返回nil

最后一步是显示结果,如果指定的用户已登录,则退出循环。

loop do
  print "Username: "
  name = gets.chomp
  found = users.find { |h| h[:username] == name }
  puts found.nil? ? "Please try again" : "Succesfully Logged In"
  break unless found.nil?
end

这里是一个示例对话:

Username: bob
Please try again
Username: sue
Please try again
Username: jack
Succesfully Logged In

1
投票

根据您的逻辑,您将从第一个元素的循环中break。我想您应该更改一下。

© www.soinside.com 2019 - 2024. All rights reserved.