# How do I find a minimal element of an array? Ruby gives me an error

Page 1 of 1

## 3 Replies - 5851 Views - Last Post: 25 March 2012 - 01:51 AMRate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=272307&amp;s=a1d4b3dbb0e7a3f01f03447cdb07a019&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 tetroel

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

# How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 11:34 AM

so i have an array

```m=Array.new(20)
for i in 1..20
m[i]=rand(1001)
end
puts m.min
```

if i try to run it, ruby says:

What's wrong with my code?
Is This A Good Question/Topic? 0

## Replies To: How do I find a minimal element of an array? Ruby gives me an error

### #2 Atli

Reputation: 4240
• Posts: 7,216
• Joined: 08-June 10

## Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 01:24 PM

POPULAR

You are looping through 1 to 20, assigning each element in the array at those indexes a random number. However arrays are zero-indexed, which means you are skipping the first index: 0. This is causing the min call to fail.

To fix this, loop through 0 to 19 instead.

You can also simplify this by doing:
```m=Array.new(20) {|i| rand(1001)}
puts m.min

```

Each element in the new array will then be initialized with a random number.

### #3 xclite

• I wrote you an code

Reputation: 1266
• Posts: 4,064
• Joined: 12-May 09

## Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 01:26 PM

So, arrays are indexed starting at 0. You create an array of size 20. Then you initialize the elements at index 1 to 20 to a number. Then you calculate the minimum, which includes the element at index 0...

[nil, rand(1001), rand(1001).... and so on]

You want to change the for i in 1..20 to for i in 0..19

Atli's solution is more idiomatic, while mine just changes the numbers.

This post has been edited by xclite: 24 March 2012 - 01:26 PM

### #4 tetroel

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

## Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 25 March 2012 - 01:51 AM

Thank you guys very much!!!