Code error about using inc function

just wondering why this code doesn’t work.

live_loop :foo do |a|
  puts a
  sleep 1
  inc a
  sleep 1

if I remove the 2nd sleep 1 command, the code works, it would prints out 1,2,3,4…but if it just runs as shown above, it will show undefined method ‘+’. I am kind of perplexed about it.


Hi Shawn!

From the live_loop entry in the Lang section of the Sonic-Pi Help documentation:

If the live_loop block is given a parameter, this is given the result of the last run of the loop (with initial value either being 0 or an init arg). This allows you to ‘thread’ values across loops.

Ruby is slightly peculiar in that the return value of the last line of a function or block is taken to be its result.

With this knowledge, we can observe that the return value of inc a is the incremented value of a. The return value of sleep given any non-zero argument is an empty hash {} (it’s nil if the argument is 0). We can also predict that if the result of the loop block were a constant number like say 5, the program would simply output 5 again and again. Don’t take my word for it; let’s try!

Ta-da :magic_wand: :sparkles:

One last note: the specific error message you’re getting is because the + operator is undefined for hashes. Hashes can be, by the way, a very useful data structure.

Happy coding!


Thanks. I will have to order a book on Ruby. Looks like it’s a necessity to know Ruby if one wants to be proficient in using Sonic Pi. Appreciate the example that you are giving, it’s making things a lot clear now.

You’re welcome. Do note that much of the Ruby language does not work with Sonic-Pi’s core libraries. This includes all object-oriented features of the language. You won’t be able to easily create classes or use def to create methods. This omission was a conscious decision by the Sonic-Pi team.

There are ways, but those are a bit more advanced and require a firm understanding of the fundamentals. I can link you to projects if you’re interested :shushing_face: I don’t think you’ll need the knowledge until your projects begin exceeding the Sonic-Pi environment buffer though.

wow, good to know. I thought Sonic PI modules would be fully compatible with Ruby language. Yes, I will have to get myself knowledgeable in Sonic Pi first before diving more complex concepts. Thanks again!

Anytime! You can do it! I can’t wait to hear what you come up with! :smile:

1 Like