Letters1 = Array["A","B"]
password1 = nil
while password1 != "A"
letter1 = Letters1[rand(0...2)]
letter2 = Letters1[rand(0...2)]
password1 = (letter1)
File.write("passwords.txt",password1)
puts password1
end
Letters1 = Array["A","B"]
password1 = nil
while password1 != "AB"
letter1 = Letters1[rand(0...2)]
letter2 = Letters1[rand(0...2)]
password1 = (letter1, letter2)
File.write("passwords.txt",password1)
puts password1
end
如何将两个数组值分配给一个变量?
我实际上尝试用=代替(。 密码1 =(字母1,字母2 = 密码1) 但它实际上并没有打印出任何东西,并且当password1的值为“AB”时它应该结束循环并且它不会结束。
“password1 = (letter1, letter2)”在 Ruby 中不是有效语法,因此会抛出错误
虽然
“密码1 =(字母1)”是。
要连接字符串,请使用
password1 = letter1 + letter2
或 join 方法。
代码可以进行一些其他调整 - 下面给出的示例
sample
方法从数组中随机选择Letters1 = ["A", "B"]
password1 = nil
fh = File.open("passwords.txt", "a" )
while password1 != "AB"
letter1 = Letters1.sample
letter2 = Letters1.sample
password1 = letter1 + letter2
fh.puts( password1 + "\n" )
puts password1
end
fh.close()