DEV Community

thomasprinn
thomasprinn

Posted on

TIL (Ruby) Each

I feel that the array and each sections were the most difficult for me, but when they clicked, they really clicked!

For example, I initially struggled with figuring out how to count and compare the number of characters to the word they were a part of, as seen in lesson 76 for the letter count activity:

word = ["photo", "like", "commenter"].sample
sample_word = word.to_s

sample_word.split("").each do |sns_component|
    pp sns_component + " appears " + sample_word.count(sns_component).to_s + " times"

end
Enter fullscreen mode Exit fullscreen mode

This is my completed code, and it works, but I found it necessary to write out my understanding for future reference.

When I used sample_word.split("") in the do loop, the word was split into a new array consisting of individual letters. This new array needs to have its' elements individually counted in order to complete the activity.

So when I went to print the statement and used .count(), adding sns_component into those parentheses allowed the code to look at the number of times each of the new elements in the new array (individual letters) occur in sns_component (which concerns the original array at the start of my code, and contains whole words for elements).

This was a great example of understanding what I needed to do, but not being entirely sure how to do it until I went, "what if I tried this?" with .count(sns_component). It feels rather obvious in hindsight, but these exercises were very similar to a recent interview I had (and struggled with) so being able to talk myself through it on my own was a great breakthrough.

At the very least, I hope that's the correct way to speak about it - maybe I'll look back and wonder why I thought of things in such a complicated matter when I improve!

Top comments (0)