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

Ruby: looping over content of an array or hash twice ?

Hi guys,

I'm working my way through the Odin Project's Ruby Building Block exercise and am currently stuck at Caesar Cypher

Here's the code:

def caesar_cipher(string, interval)
  cipherlist = []
  cipherlist = string.split()
  cipherlist.each do |word|
    word.each do |letter|
      print letter
    end
  end

end  

caesar_cipher("What a string!", 5) "Bmfy f xywnsl!"

Since I'm currently more familiar with Python than with Ruby, I tend to approach things with that point of view. For instance in Python it is possible to do the following:

cipherlist = ["What", "a", "string!"]
for word in cipherlist;
    for letter in word:
        print letter

This would result in an output that displays every single letter of the array on a single line. The printing is just a test and I plan to convert every single letter in that inner loop to an integer and then add a value (the second argument passed to the caesar_cipher function) to it, after which I will plug everything back into a different array and solve the problem. I just can't seem to figure out how to do this in Ruby. (without cheating and looking at other people's solution) Any feedback is welcome! Thanks in advance.

1 Answer

For starters, I would use these two methods:

.ord - converts characters to their numerical representation

2.1.2 :001 > "a".ord
 => 97 

.chr - converts numbers back to character representation

2.1.2 :002 > 97.chr
 => "a" 
2.1.2 :003 > 98.chr
 => "b" 

You put things into arrays easily like this:

2.1.2 :004 > a = []
 => [] 
2.1.2 :005 > a << 5
 => [5] 
2.1.2 :006 > a << "N"
 => [5, "N"] 
2.1.2 :007 > a << 3.14
 => [5, "N", 3.14]