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
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).
The "each" method in Ruby on Rails allows you to iterate over different objects inside an array-like structure.
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.
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.
I have a nicer method: use the splat operator!
[*'0'..'9', *'a'..'z', *'A'..'Z'].sample(16).join
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With