Array.random_index

Sepertinya core ruby developer sudah harus menambahkan fungsi ini pada class Array, karena gw sering banget lihat fungsi ini digunakan pada real code

class Array
  def rand_i
    return self[rand(self.size)]
  end
end

Let’s kick some test:

love = %w(saya cinta roy suryo)
result = []
result << love.rand_i
result << love.rand_i
result << love.rand_i
result << love.rand_i

print result.join(" ")

Output?!

C:\> rand_array.rb

roy suryo cinta saya

Well, don’t look at me, blame the system…

Advertisements

One thought on “Array.random_index

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s