I’m working through a tutorial and Ive come across a line of code that I
do not understand. The program basically takes a roman number value and
converts it to its integer counterpart.
Here is the line:
roman_string.to_s.upcase.split(//).reverse.inject(0) do |memo, digit|
If roman_string contains the value “IV”, when we come to this line can
you please explain what the ‘inject’ does? When I step through it in
debug mode, I can see it gets assigned ‘0’. But how is the ‘digit’
populated? How does it know it gets the ‘V’ first and subsequently ‘I’?
Does it do this by default because the inject(0) populates the memo so
the only variable left is digit?
I tried to play around, by removing the ‘.inject(0)’ and the ‘memo’ to
see if I could understand what it was doing but to no avail.
roman_string.to_s.upcase.split(//).reverse. do |digit| # program balks
If you’d like me to post the whole program I could, but I didnt want to
clutter the post.