Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two different 'ranges' to one in ruby

I want to combine two different ranges in rails into a single array. Is there any short method for the same?

I am writing code to generate random alpha-numeric strings.

Right now I have:

('a'..'z').to_a.shuffle.first(16).join

I have also tried something like this (which did not work):

('a'..'z').to_a.push('0'..'9').shuffle.first(16).join
like image 345
Radhika Avatar asked Jan 28 '14 11:01

Radhika


People also ask

How do I merge two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

What does the .each method do in Ruby?

The "each" method in Ruby on Rails allows you to iterate over different objects inside an array-like structure.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

How do you create a range of numbers in Ruby?

Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.


1 Answers

I have a nicer method: use the splat operator!

[*'0'..'9', *'a'..'z', *'A'..'Z'].sample(16).join
like image 193
kmikael Avatar answered Nov 16 '22 02:11

kmikael