1 Replies - 2264 Views - Last Post: 28 March 2012 - 01:54 AM Rate Topic: -----

#1 tetroel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-March 12

Couldn't you explain me how does this little code work?

Posted 28 March 2012 - 12:33 AM

n = gets.chomp.to_i
puts (1..n).to_a.to_s.each_char.inject(0){|sum, d| sum += d.to_i}


I'm particularly interested in the second string of the code.
Is This A Good Question/Topic? 0
  • +

Replies To: Couldn't you explain me how does this little code work?

#2 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 251
  • View blog
  • Posts: 640
  • Joined: 01-March 09

Re: Couldn't you explain me how does this little code work?

Posted 28 March 2012 - 01:54 AM

Basically, it works by converting a range of integers into an array, then a string. Then, using inject, it goes through and reduces the string by summing up all the integers two at a time. The Ruby documentation could definitely give you some better in-depth information about what exactly is happening. This code can be simplified and looks like it was purposely made to be over-complicated.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1