# .each.with\_index?

**URL:** <https://in-thread.sonic-pi.net/t/each-with-index/6845>\
**Category:** General\
**Created:** [June 9, 2022, 5:20pm UTC](https://in-thread.sonic-pi.net/t/each-with-index/6845 "2022-06-09T17:20:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Eli](https://dub1.discourse-cdn.com/flex017/user_avatar/in-thread.sonic-pi.net/eli/32/116_2.png) [@Eli](https://in-thread.sonic-pi.net/u/Eli)\
**Post date:** [June 9, 2022, 5:20pm UTC](https://in-thread.sonic-pi.net/t/each-with-index/6845/1 "2022-06-09T17:20:56Z")

</div>

EDIT: To save you some reading… I had an extra line of items in bass\_notes, once removed,  
everything works fine… sorry for the dumbness. 🙂

Hi folks,

I’m doing some tinkering with the code provided by @Ludvig in this thread:

> [@Lofi house, my first code](https://in-thread.sonic-pi.net/t/lofi-house-my-first-code/6834):
>
> Hey everybody! Just started messing around with Sonic PI, so much fun! I can already tell that this is a really good tool for breaking out of creative blocks. Here’s my first little thing I made, a sort of chill out house beat with a live mixer for muting different instruments. Any feedback on how to write it cleaner would be highly appreciated slightly_smiling_face # PROJECT SETTINGS use\_bpm 118 live\_loop :met1 do sleep 1 end # SEQUENCER SETTINGS define :pattern do |pattern| return …

At the bottom of his code is a long live loop :Bassline with lots of calls to a define:

So far I’ve collected all the paramters passed in the calls to two arrays:

```ruby
bass_note = [29,34,36,39,41,
              29,34,36,41,39,34,
              36,29,31,34,39,
              36,41,43,36,34,29,
              27,32,34,37,39,
              27,32,34,39,37,32,
              34,27,29,32,37,
              34,39,41,34,32,37,
              34,39,41,34,32,27]

bass_rel = [0.75,0.75,1,1,0.5,
              0.75,0.75,1,0.5,0.5,0.5,
              0.75,0.75,1,1,0.5,
              0.75,0.75,1,0.5,0.5,0.5,
              0.75,0.75,1,1,0.5,
              0.75,0.75,1,0.5,0.5,0.5,
              0.75,0.75,1,0.5,0.5,0.5]

loops = [1,1,1,1,1,1,0,0,0]

bass = 4

```

And rewritten the define basn as follows:

```ruby
define :basn do |n, r|
  n.each.with_index do |n, id|
    # if loops[bass] is changed while this is playing, the next
    # line lets the define break out and return.
    if loops[bass] == 0 then
      return
    else
      play n, release: r[id], cutoff: rrand(55, 125)
      sleep r[id]
    end
  end
end

```

Here’s the problem. I have very little experience with indexing, so I dont know  
how to tick through the value of r, that is relevant to the value of n…

The way I’m doing it, the bassline plays for a while then stops with  
‘nil can’t be coerced into a float’… maybe I have mismatch in the  
number of items I’m passing in the arrays?

Help figuring this out would be appreciated, as it drops about  
70 lines of code from Luddies original.

Many thanks,

Eli…
