Confusing Ruby with Javascript (4/6)


#1

I'm having trouble with exercise 4...because I am perhaps being absentminded and can't remember how to print the length of a string. So, out of frustration, I tried "words.length" and obviously it didn't work, but it was worth a shot.

Here's what I have:

puts "Your input here:"
text = gets.chomp
puts "Your other input here:"
redact = gets.chomp
words = text.split(" ")

words.each do |x|
    x = words.length
    print x
end

I know that wouldn't even work, but basically...I'm not sure how to get it to print each of the words without turning it into an array. Is that what I have to do? How do you have it go through the array afterwards?


#2

Update: I've figured it out, because I was apparently over-complicating, but I'm honestly not sure why it works.

puts "Your input here:"
text = gets.chomp
puts "Your other input here:"
redact = gets.chomp
words = text.split(" ")

words.each do |words|
    print words
end

The first part is very straightforward; the second isn't, to me. Can someone break down the .each for me to help me understand why it works by using the same variable, when the explanation says that it has to be a placeholder? Why can the placeholder be the same as the original? In which case, why can't you just say "print words" without the placeholder part, if it's exactly the same?


#3
words.each do |words|
    print words
end

It's probably not a good idea to use the object name for a placeholder (iterator, actually).

words.each do |word|
    print word
end

This makes more sense to me. How about you?


#4

That's actually why I was so confused! It didn't make sense to me why it worked -- I've always learned it's a bad idea to re-use variable names and such -- but it was the only way I could get it to work. I tried with the way you had written it, and it just gave me errors.

Perhaps I have a misunderstanding over the function of the iterator? Is it a second variable type of thing?


#5

Yes, a second, throw away variable, unlike the object reference which we would want to protect. I'm not sure why your code wouldn't work with the suggested variable. It could be any variable, x, thor, holy_thunderer; it shouldn't matter.