Convert string into Array in rails - ruby-on-rails

I send an array from rest client and received it like this: "[1,2,3,4,5]"
Now I just want to convert it into Array without using Ruby's eval method. Any Ruby's default method that we could use for this?
"[1,2,3,4,5]" => [1,2,3,4,5]

require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]

Perhaps this?
s.tr('[]', '').split(',').map(&:to_i)

If you want to avoid eval, yet another way:
"[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]

Related

Merge subarrays into single one and remove duplicates if they have same id using ruby on rails

I have an array of arrays like this:
array = [[1, 'Something', '123456321'], [2, 'Something', '123456321'], [2, 'Something', '1234563212']]
And I want to merge the subarrays that have same id and get this result:
array = [[1, 'Something', '123456321'], [2, 'Something, Something', '123456321, 1234563212']]
Can anyone help me? Thanks!
array.group_by(&:first).map do |id, records|
names = records.map(&:second).join(', ')
values = records.map(&:last).join(', ')
[id, names, values]
end
As you asked the reversed question recently, I suggest you to read the Enumerable, Array, Hash and String documentations. It will give you an instant boost in expressiveness and understanding of how to do common tasks with Ruby.
Just for fun, here's a one-liner :
array.group_by(&:first).map{|i, arrays| [i] + arrays.transpose.drop(1).map{|v| v.join(', ') } }

Options for processing X elements of an array at a time using Ruby

We want to process 1000 elements of an array at a time. What are the options for doing this in Ruby?
Obviously, one approach is to do a simple loop and slice 1000 elements from the array until no more elements remain, but was curious if there are other more elegant options.
This is for a Rails app (RoR 3.2.12).
In Rails you can use in_groups_of:
array = [1,2,3,4,5,6,7,8,9,10]
array.in_groups_of(3, false).each do |group|
puts group
end
# => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
We wound up using each_slice:
array = [1,2,3,4,5,6,7,8,9,10]
array.each_slice(3) do |group|
puts group
end

Ruby Enumerator-based lazy flatten method

Michael Harrison has a great post on lazy enumerators in Ruby, providing an implementation of lazy_select and lazy_map. I am wondering whether the following implementation of lazy_flatten should have special processing for anything other than Enumerator and Enumerable types.
class Enumerator
def lazy_flatten
Enumerator.new do |yielder|
self.each do |value|
if value.kind_of? Enumerator
value.lazy_flatten.each do |v|
yielder.yield v
end
elsif value.kind_of? Enumerable
value.flatten.each do |v|
yielder.yield v
end
else
yielder.yield value
end
end
end
end
end
This doesn't seem lazy to me, as you are still performing old (non-lazy) flatten beneath.
Enumerator is Enumerable, so I think you don't need to handle it separately.
I would expect lazy_flatten to be method on Enumerable.
Here's how I would implement it:
module Enumerable
def lazy_flatten
Enumerator.new do |yielder|
each do |element|
if element.is_a? Enumerable
element.lazy_flatten.each do |e|
yielder.yield(e)
end
else
yielder.yield(element)
end
end
end
end
end
Note that in Ruby 2.0+, you don't need to do this, you can just use Enumerable#lazy, which returns an Enumerator::Lazy.
For reasons that aren't clear to me, Lazy doesn't have flatten, but it has flat_map, so in principle you could just use flat_map with the identity function.
module Enumerable
def lazy_flatten
self.lazy.flat_map { |x| x }
end
end
Lazy#flat_map mostly takes care of decomposing any decomposable elements, but not quite -- from the docs:
A value x returned by block is decomposed if either of the following conditions is true:
x responds to both each and force, which means that x is a lazy enumerator.
x is an array or responds to to_ary.
Note that to_ary is not a method on Enumerable, presumably to discourage implicit conversions from infinite sequences to arrays. This means, for instance, that if you try to lazy_flatten something that contains a Set or a Range with the above code, it (arguaby, see below) won't work:
a = [[1, 2, 3], Set[4, 5], 6, 7..8]
# => [[1, 2, 3], #<Set: {4, 5}>, 6, 7..8]
f = a.lazy_flatten
# => #<Enumerator::Lazy: #<Enumerator::Lazy: [[1, 2, 3], #<Set: {4, 5}>, 6, 7..8]>:flat_map>
f.to_a
# => [1, 2, 3, #<Set: {4, 5}>, 6, 7..8]
However, this is the same as the behavior of Array#flatten:
a.flatten
# => [1, 2, 3, #<Set: {4, 5}>, 6, 7..8]
(Although Array#flatten will not detect and decompose lazy enumerators, and Lazy#flat_map will.)
Whereas the OP's code or the code in Mladen Jablanović's answer will decompose the Set and the Range:
f = a.lazy_flatten # (M.J.'s code)
# => #<Enumerator: #<Enumerator::Generator:0x00007fd819c166c0>:each>
f.to_a
# => [1, 2, 3, 4, 5, 6, 7, 8]
That code, however, will also iterate infinitely if passed something that includes an infinite sequence:
a = [[1, 2, 3], Set[4, 5], 6, 7..8, 9..Float::INFINITY]
# => [[1, 2, 3], #<Set: {4, 5}>, 6, 7..8, 9..Infinity]
f = a.lazy_flatten # (M.J.'s code)
# => #<Enumerator: #<Enumerator::Generator:0x00007fd819a73d18>:each>
f.to_a
# => spins at 100% CPU for a while and eventually runs out of memory
If you consider that a feature, rather than a bug, one approach would be to modify the flat_map-based implementation to convert any enumerables it finds to lazy ones:
module Enumerable
def lazy_flatten
self.lazy.flat_map do |x|
x.respond_to?(:lazy) ? x.lazy : x
end
end
end
This works even for nested lazy enumerables, as Lazy#lazy is smart enough to return itself.

Retrieve x random elements from an array

I am struggling to write a clean method which when passed an array of strings and x returns a randomised list of array elements totalling x, eg.
def getrandomarrayelements(thearray, howmany)
return [something]
end
Yes I should submit my existing code, which whilst works is not good, it's 8 lines long and I have a feeling it can be done in one?!
In ruby 1.9:
irb(main):001:0> [1,2,3,4,5].sample(3)
=> [2, 4, 5]
irb(main):002:0> [1,2,3,4,5].sample(3)
=> [2, 5, 3]
and for ruby 1.8 something like this:
def sample(arr, n)
arr.shuffle[0...n]
end
irb(main):009:0> sample([1,2,3,4,5], 3)
=> [5, 1, 3]
irb(main):010:0> sample([1,2,3,4,5], 3)
=> [3, 4, 2]

#users.each do |user| --- Is there a way to do this for multiple objects

I'm currently doing:
#users.each do |user|
Given I have #users, #users1, #users2
Is there a way to do:
[#users, #users1, #users2].each do |user|
Having the each loop go through all the objects?
Thanks
You can concatenate the arrays and iterate the result:
(#users + #users1 + #users2).each do |user|
...
end
It may be tempting to use flatten, but you should be careful with it. A simple no-arguments flatten call doesn't behave the way you expect if any elements of any array are arrays themselves:
users, users1, users2 = [1,2], [ [3,4], [5,6] ], [ 7,8]
puts [users,users1,users2].flatten.inspect
# Will print [1, 2, 3, 4, 5, 6, 7, 8]
# Two small arrays are smashed!!!
However, as jleedev suggests in one of the comments, flatten function in Ruby may accept an integer argument that defines the maximum level the arrays will be smashed to, so:
puts [users,users1,users2].flatten(1).inspect
# Will print [1, 2, [3, 4], [5, 6], 7, 8]
# Just as planned.
[#users,#users1,#users2].flatten.each do |user|
Various techniques:
# Concatenate
(#users+#users1+#users2).each{ ... }
# Splat (Ruby 1.9 only)
[*#users,*#users1,*#users2].each{ ... }
# Interleave them
#users.zip( #users1, #users2 ).each{ |u,u1,u2| ... }

Resources