Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Jordany Rosas
PLUS
Jordany Rosas
Courses Plus Student 4,557 Points

Need help getting my method to work

I'm trying to create a method that takes in a string, and returns that string, but it's previous letters. For example, "afe" would return "zed"

def decrypt(string)
  string_index = 0
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  alphabet_index = 0
  new_string = ""

  while alphabet_index < string.length
    if string[string_index] == " "
      puts string[string_index] = " "
    else 
      if string[string_index] == alphabet[alphabet_index]
new_string = new_string + alphabet[alphabet_index - 1]
      end
      string_index += 1
    end 
    alphabet_index += 1
  end
  puts new_string
end
decrypt("aje")

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

This is a little tricky to debug. Part of the problem is telling the difference between alphabet_index and string_index.

A more idiomatic way to do this would be to create an array of letters and use the each method to loop over them. That way you don't have to mess with incrementing or checking an index. Or in this case, since you're using a String, you can use the each_char method to get the same effect. Here's a snippet:

"aje".each_char do |letter|
  puts letter
end

Outputs:

a
j
e

See if that gets you unstuck.

Jason Seifer covers each in Stage 2 of our Ruby Loops course.