Ruby 未触发条件语句
我写了一段代码,根据输入创建一个随机字符串。用户决定其长度以及是否应包含数字和特殊字符。我添加了一个故障安全例程,因为最终结果是随机的:Ruby 未触发条件语句,ruby,if-statement,Ruby,If Statement,我写了一段代码,根据输入创建一个随机字符串。用户决定其长度以及是否应包含数字和特殊字符。我添加了一个故障安全例程,因为最终结果是随机的: def create i = @number while i != 0 # testing the script I have noticed that the if statement is (always) ignored. if i == 2 && (@word_bank.include?(@special_cha
def create
i = @number
while i != 0
# testing the script I have noticed that the if statement is (always) ignored.
if i == 2 && (@word_bank.include?(@special_chars) && @rand_ary.include?(@special_chars) == false)
@rand_ary << @special_chars[rand(0..@special_chars.size - 1)]
end
letter = rand(0..word_bank.size - 1)
#puts "#{i}, #{word_bank[letter]}"
@rand_ary << word_bank[letter]
word_bank.delete_at(letter)
i -= 1
end
@rand_string = @rand_ary.join()
puts @rand_string
@rand_string
end
def创建
i=@number
而我0
#在测试脚本时,我注意到if语句(总是)被忽略。
如果i==2&(@word\u bank.include?(@special\u chars)和&@rand\u ary.include?(@special\u chars)==false)
@随机变量如果您的变量具有我认为它们具有的值,那是因为include
不是这里使用的正确方法
如果@word\u bank
和@rand\u ary
是数组,include
将检查是否有任何单个元素等于@special\u chars
。如果@special\u chars
本身是一个数组,那么只有当@word\u bank
/@rand\u ary
中的一个元素是数组时,它才会返回true
['a', 'b', 'c', '!'].include?('!') # => true
['a', 'b', 'c', '!'].include?(['!']) # => false
['a', 'b', 'c', ['!']].include?(['!']) # => true
我想你实际上对它们之间是否有重叠感兴趣。在这种情况下,您可以使用交叉点(&
)操作符检查它是否为空
['a', 'b', 'c', '!'] & ['!'] # => ['!']
['a', 'b', 'c'] & ['!'] # => []
可能是因为条件i==2&(@word\u bank.include?(@special\u chars)和&&rand\u ary.include?(@special\u chars)==false)
总是返回false
;)Fabio不@word\u bank.include(@special\u chars)
翻译成@word\u bank.include(@special\u chars)==true
?两种版本我都试过了,但都没用(选择使用第一个版本b/c,它更像ruby风格……我错了吗?在ruby中很少需要说x==false
,这只在区分nil
和false
时才重要。相反,说!x
基于@rand\u-ary@Max@word\u-bank
+@rand\u-ary
是机器人h数组。要问你如何将&
合并到if语句中
简洁?使用google和ruby Doc在这方面有困难的话,你也可以['a','b','c','!'].grep('!')
,它也可以使用正则表达式,以更灵活。我刚刚尝试了if I==2&(@word\u-bank&@special\u-chars&&@password\u-ary&@special\u-chars==false)
第一次测试失败了…@foo这就像是if!(@word\u-bank&@special\u-chars)。第一个条件为空?
。