In w§gtr I have found myself facing a code which, for the life of me,
I just could not understand a few thing in! Seeing as this is the
closest board realting to the subject, I shall post my question here -
def name_significance
parts = self.split( ‘-’ )
syllables = @@syllables.dup
signif = parts.collect do |p|
syllables.shift[p]
end
signif.join( ’ ’ )
end
end
Now, what I could not understand is:
Why is @@syllables divided into two hashes? Why is it an array in the
first place?
And secondly, “syllables.shift[p]”. Playing around I gathered that the
.shift[p] method returns the result of hash[p] and extracts the pair
from the hash. Yet I was told that the [p] part isn’t an argument! So I
can’t seem to fully understand this code…
It doesn’t seem to work when I join the two hashes into one, and, again,
I can’t understand why.
It is probably just a little thing I’m missing, or some-such event. If
anyone could be of assistance, I will be very grateful.
Why is @@syllables divided into two hashes? Why is it an array in the
first place?
One hash for the first part of the name and one hash for the second, I
assume.
And secondly, “syllables.shift[p]”. Playing around I gathered that the
.shift[p] method returns the result of hash[p] and extracts the pair
from the hash.
First of all there is no shift[p] method. There’s just the shift method.
And
when you were “gathering around” you were asking about the Hash#shift
method
which is not used here. The code calls shift on the array, not on the
hash.
shift will return the first hash the first time and the second hash the
second time. Then you call [p] on that hash. I.e. you take the value
from the
hash whose key equals p.
Yet I was told that the [p] part isn’t an argument! So I
can’t seem to fully understand this code…
See above.
It doesn’t seem to work when I join the two hashes into one, and, again,
I can’t understand why.
Yes, because then you actually call shift on the hash and not on an
array and
the return value will be one key-value pair and not a hash. Then you try
to
call [p] on that key-value pair, but that doesn’t work, because you
could
only call [0] or [1] on it, but not [“somestring”], but p will be a
string
here.
And when you were “gathering around” you were asking about the Hash#shift
method which is not used here. The code calls shift on the array, not on the >hash.
You’re right. I didn’t fully understand that.
I didn’t mean to imply that the help I received on IRC wasn’t
worthwhile, just that in the end I got confused because of my lack of
understanding.
One again, thank you!
It’s great that there people who help like you.
-Gill
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.