Ruby: “string not matched”

January 3, 2008 at 9:35

Filed under: Computing — Pistos @ 09:35

I was debugging a Reby script and came across a most unusual error:

Reby error: string not matched
chanstats.rb:43:in `[]=’

Line 43 was:

@stats[ channel ][ :size_record ] ||= 0

which looks rather innocuous. I have a couple Hashes, one nested in the other. Or so I thought… Apparently, I had mistakenly initialized @stats with a string instead of a Hash. Testing in irb, everything becomes clear:

irb(main):001:0> s = "string"
=> "string"
irb(main):006:0> s[ 'hi' ] = 'foo'
IndexError: string not matched
        from (irb):6:in `[]='

I hope this helps people who can’t figure out why they’re getting “string not matched”.

Share This

1 Comment »

  1. Comment by qneill — June 13, 2008 @ 16:45

    Thanks for the post.

    I ran into the same conundrum trying to use “inject” to convert an array of arrays to a hash. I guess this is purely a tangential story, but here it goes anyway. I was trying to get from

      a = [ ["1","one"], ["2","two"]
    

    to

      h = { "1"=>"one", "2"=>"two" }
    

    Following the Enumerable inject example from rubydoc:

      (5..10).inject(1) {|product, n| product * n }
    

    I tried:

      a.inject({}) { |h,n| h[n[0]] = n[1] }
    

    which resulted in

      IndexError: string not matched
    

    After debugging with lots of “puts” calls, I figured out that each time the block is executed, the result is passed to the next block. In my bad example, h started out as a Hash, but the next time h was the string “one” resulting from the assignment in the first block execution.

    The fix was to return the hash after the assignment for each block:

      a.inject({}) { |h,n| h[n[0]] = n[1]; h }
    

RSS feed for comments on this post. TrackBack URI

Leave a comment

You may use Markdown syntax in your comment.

Powered by WP Hashcash

Powered by WordPress.
Close
E-mail It
Socialized through Gregarious 42