I’m reading through part 1, blocks and iterators section. Lots to
digest here
Anyway, there is discussion about implementing a search for songs,
called ‘with_title’
Even though the first code example is not the one that ultimately gets
used I think for me it’s important to understand it, so I tried
recreating it outside the actual application. I’m getting some errors
and would appreciate some feedback.
Here is the code (I’ve used some puts statements to see what’s going on)
def with_title (title)
myarray = [‘Ruby Tuesday’, ‘Paint it Black’, ‘Lets Spend the Night
Together’,
‘Mothers Little Helper’, ‘Jumpin Jack Flash’]
for i in 0…myarray.length
puts myarray.length # added in to debug
puts 'here is i: ' + i.to_s # added in to
debug
return myarray[i] if title == myarray[i].title
#leaving .title in causes an error
#about undefined method
puts 'here is myarray[i] ' + myarray[i]
end
end
with_title('Paint it Black')
If in this line
return myarray[i] if title == myarray[i].title <------ I removed the
.title from the right side of
the equality statement, myarray[i]
I get this back:
5
here is i: 0
here is myarray[i] Ruby Tuesday
5
here is i: 1
What it does is call the #title method on myarray[i], but in your
example, myarray[i] is a String, which doesn’t have a #title method -
hence, undefined method. I believe (my copy is at the office) that
the example in the book uses a Song class which has the title method
defined.
the equality statement, myarray[i]
I get this back:
5
here is i: 0
here is myarray[i] Ruby Tuesday
5
here is i: 1
Which is exactly what I’d expect. myarray[1] is ‘Paint it Black’.
The next statement after printing ‘here is i: 1’ is to return the
current title if it matches the title being searched for. They
match, so the method returns.
The usual idiom in Ruby omits explicit return statements, and relies
on the language to return the value of the final expression evaluated
in the method. An explicit return statement exits the method,
returning the specified value immediately. In this case, it’s used
as a way to stop the loop once a match is found, presumably with the
assumption that either you only need the first match, or that only
one will exist.
Thank you , that helps! The part that was throwing me was the ‘Ruby
Tuesday’ myarray[0], I’m gathering since it’s the first to come before
the puts statement it shows.
Stuart
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.