【问题标题】:Concatenated string does not equal literal string?连接字符串不等于文字字符串?
【发布时间】:2014-03-18 01:00:20
【问题描述】:

我正在尝试使用正则表达式并在 ruby​​ 中测试我自己的代码。使用下面的示例,我预计最终的 puts 会返回 true,但事实并非如此。但是,check_password 方法会返回“您的密码太短,无法正常工作”。为什么真/假检查不返回 true?

def err_message(reason)
  puts "Your pw does not work because " + reason
end

def check_password(password)
    if password.length<6
        return err_message("it is too short")
    elsif password.index(/[A-Z]/)==nil
        return err_message("it does not contain a capital letter")
    elsif password.index(/\d|[!,@,#,$,%,&,*,+,:,?]/)==nil
        return err_message("it needs either a digit or special character")
    elsif password.index(/([!,@,#,$,%,&,*,+,:,?\w])/)>0
        return err_message("nope. !,@,#,$,%,&,*,+,:,? are the only special characters available")
    else
        return "Valid Password!"
    end
end

puts check_password("aaaaa")=="Your pw does not work because it is too short"

【问题讨论】:

    标签: ruby string equality


    【解决方案1】:

    err_message 将评估puts "Your pw does not work because " + reason 并返回nil,因为nilputs 的返回值,请将方法定义更改为如下所示:

    def err_message(reason)
      "Your pw does not work because " + reason
    end
    

    然后:

    puts check_password("aaaaa")=="Your pw does not work because it is too short"
    # => true
    

    【讨论】:

    • 添加的方法是考虑到没有添加的多个验证。有什么想法吗?
    • 我不确定我理解你的意思??
    【解决方案2】:

    以下是一些改进方法的建议。通常我会加上评论,但格式限制在这种情况下不切实际。考虑这样写:

    SPECIAL_CHARS = '!@#$%&*+:?'
    
    def check_password(password)
      "Your pw does not work because " +
      case
      when password.length < 6
        "it is too short"
      when password.match(/[A-Z]/).nil?
        "it does not contain a capital letter"
      when password.match(/\d|[{SPECIAL_CHARS}]/).nil?
        "it needs either a digit or special char"
      else
        return "Valid Password!"
      end
    end  
    
    check_password("abcde")
      #=> "Your pw does not work because it is too short" 
    check_password("abcdef")
      #=> "Your pw does not work because it does not contain a capital letter"
    check_password("abcdeF")
      #=> "Your pw does not work because it needs either a digit or special char"
    check_password("abcdeF@")
      #=> "Valid Password!"
    check_password("abcdeF1")
      #=> "Valid Password!"
    

    我删除了

      when password.index(/([!,@,#,$,%,&,*,+,:,?\w])/) > 0
        "nope. !,@,#,$,%,&,*,+,:,? are the only special characters available"    
    

    因为我不明白它在检查什么。

    注意return只有一个,也就是密码有效的时候。如果密码无效,则将 case 语句的结果(字符串)添加到字符串 "Your pw does not work because " 并返回(因为这将是该方法执行的最后一条语句——不需要 return) .

    我将index 替换为match,不过您也可以这样写:

    when !(password =~ /[A-Z]/)
    

    when !password[/[A-Z]/]
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2023-03-27
      • 2017-12-29
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      相关资源
      最近更新 更多