lylesconstant lylesconstant - 2 months ago 6
Ruby Question

Ruby encryption program giving me mixed results

I wrote this program to take a name, reverse the first and last name, and move the letters over by one. When I run it, it runs fine, except that at the end it spits out each name with an alias of every other name's aliases. They seem to be exponential, if I have three aliases, I get nine results. Please help me. New to ruby.

@aliases = []
@real = []

def alias_machine(name)
@real << name
name = name.downcase
name_array = name.split(' ')
first_name = name_array[1]
first_name_split = first_name.split('')
last_name = name_array[0]
new_namearray1 = first_name_split.map do |y|
vowels = ["a", "e", "i", "o", "u"]
if y == vowels[0]
y = "e"
elsif y == vowels[1]
y = "i"
elsif y == vowels[2]
y = "o"
elsif y == vowels[3]
y = "u"
elsif y == vowels[4]
y = "a"
elsif y.next == "aa"
y = "b"
elsif y.next == vowels[1]
y = y.next.next
elsif y.next == vowels[2]
y = y.next.next
elsif y.next == vowels[3]
y = y.next.next
elsif y.next == vowels[4]
y = y.next.next
else
y = y.next
end
end
last_name_split = last_name.split('')
new_namearray2 = last_name_split.map do |y|
vowels = ["a", "e", "i", "o", "u"]
if y == vowels[0]
y = "e"
elsif y == vowels[1]
y = "i"
elsif y == vowels[2]
y = "o"
elsif y == vowels[3]
y = "u"
elsif y == vowels[4]
y = "a"
elsif y.next == "aa"
y = "b"
elsif y.next == vowels[1]
y = y.next.next
elsif y == vowels[2]
y.next.next
elsif y.next == vowels[3]
y = y.next.next
elsif y.next == vowels[4]
y= y.next.next
else
y = y.next
end
end


new_namearray1 = new_namearray1.join('')
new_namearray1 = new_namearray1 + " "
new_namearray1 = new_namearray1.capitalize
new_namearray2 = new_namearray2.join
new_namearray2 = new_namearray2.capitalize
lastarray = []
lastarray[0] = new_namearray1
lastarray[1] = new_namearray2
lastarray = lastarray.join
@aliases << lastarray
end

loop do
p "Give us a name"
names = gets.chomp
if names == "Quit"
p "Thanks!"
@aliases.each do |aliases|
@real.each do |real|
p "#{aliases} is actually #{real}"
end
end
break
else
alias_machine(names)
end
end

Answer

For each name you append the real name and the alias to each corresponding variable. When the program quits, you iterate over the combination of both. Thus you get the exponential result.

@aliases.each do |aliases|
  @real.each do |real|
    p "#{aliases} is actually #{real}"
  end
end

You probably only want one variable with an array. You can store the pair using this command:

@aliases << [name, lastarray]

and read it again:

@aliases.each do |name, alias|
  p "#{alias} is actually #{name}" 
end
Comments