我制作了一个程序,我需要将所有可能的字符放在一个数组中。 在这里我创建我的变量只是为了读取名称
print "write your name: "
name1 = gets.chomp
然后我尝试将所有字符放在数组中,例如,如果你的名字是John,数组将是:J,Jo,Joh,john
arrayNames = []
number = name1.length
number.times {|i|
arrayNames[i] = name1.slice(0,i)
}
arrayNames << name1
然后阅读它,我想制作一个排列程序,我写道:
numb = name1.length+ 1
numb2 = anotherVariable.length + 1
numb.times {|j|
numb2.times {|k|
perm = [arrayNames[j],theSecondArray[k]]
p perm
file1.puts
}
}
当然我已经制作了file1,并且我拥有与arrayNames
完全相同的第二个数组代码,但是不起作用。它甚至没有显示错误。生病将所有代码放在一起
class Data
def initialize
end
def dataIn
print "write your name: "
$name = gets.chomp
print "write your surname: "
$surname = gets.chomp
end
def dataName
$passwordName = []
numb = $name.length
numb.times {|i|
$passwordName[i] = $name.slice(0,i)
$passwordName << $name
end
def dataSurn
$passwordSur = []
numb = $surname.length
numb.times {|i|
$passwordSur[i] = $surname.slice(0,i)
}
$passwordSur << $surname
end
def alg1
numb = $name.length + 1
numb2 = $surname.length + 1
numb.times {|i|
numb2.times {|j|
perm = [$passwordName[i], $passwordSur[j]].permutation.map {|k|
k.join}
p perm
$archivos.puts perm
}
}
end
end
代码本身有点复杂,但我的问题是一样的。方法alg1不工作。然后我只是调用它们并创建文件
data = Data.new()
datos.dataIn
$archivos = File.new("passwords",'w+')
File.open("passwords")
data.datosName
data.datosSurn
data.alg1
gets()
答案 0 :(得分:0)
我不确定你要做什么,但Ruby的内置数组方法将让你的生活更轻松:
>> name1 = 'John'
=> "John"
>> names = (0...name1.length).map { |i| name1[0..i] }
=> ["J", "Jo", "Joh", "John"]
>> other = ['dog', 'wolf', 'sheep']
=> ["dog", "wolf", "sheep"]
>> result = names.product(other)
=> [["J", "dog"],
["J", "wolf"],
["J", "sheep"],
["Jo", "dog"],
["Jo", "wolf"],
["Jo", "sheep"],
["Joh", "dog"],
["Joh", "wolf"],
["Joh", "sheep"],
["John", "dog"],
["John", "wolf"],
["John", "sheep"]]