Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to loop through an object that may or may not be an array?

Tags:

arrays

loops

ruby

I have an each method that is run on some user-submitted data.

Sometimes it will be an array, other times it won't be.

Example submission:

<numbers>
    <number>12345</number>
</numbers>

Another example:

<numbers>
    <number>12345</number>
    <number>09876</number>
</numbers>

I have been trying to do an each do on that, but when there is only one number I get a TypeError (Symbol as array index) error.

like image 871
Shpigford Avatar asked Jun 28 '26 04:06

Shpigford


1 Answers

I recently asked a question that was tangentally similar. You can easily force any Ruby object into an array using Array.

p Array([1,2,3]) #-> [1,2,3]
p Array(123)     #-> [123]

Of course, arrays respond to each. So if you force everying into an array, your problem should be solved.

like image 186
Shadowfirebird Avatar answered Jul 01 '26 00:07

Shadowfirebird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!