Fetch similar values from an Array in ruby - ruby-on-rails

I have an array
sample_array = [10001567, 10001789, 2347800, 10001534, 64786592, 00000355]
output_array = [10001567, 10001789, 10001534]
I need to fetch all the elements into a new array where the first 5 digits must be same in a given array. How to do this in ruby.

sample_array = [10001567, 10001789, 2347800, 10001534, 64786592]
patterns = sample_array.group_by { |el| el.to_s.chars.first(5).join.to_i }
=> {10001=>[10001567, 10001789, 10001534], 23478=>[2347800], 64786=>[64786592]}
UPDATE
Selecting the pattern for this specific case
patterns.select{|_,v| v.size > 1}.values.flatten

Related

Remove/delete object from array in Ruby based on attribute value

I have an array
result = [{:cluster=>[0, 4], :id=>1, :units=>346, :num1=>0.161930681e7, :num2=>0.14223512616e9, "description"=>"Foo"}, { ...
And I want to take out any objects with number of units equal to 0. Looking for something similar to array.splice() but for Ruby
What is the best way to do this ?
You can use the #reject method to return the array without objects whose :units equals 0:
result.reject { |hash| hash[:units] == 0 }
There's also #reject! and #delete_if, which can be used in the same way as above but both modify the array in place.
Hope this helps!
You can achieve the same result using select method implemented on the Array class:
result.select { |el| el[:units] == 0 }

DynamoDB: How to use a filter expression on ios (single column with multiple value)?

I am new in Amazon Web Services. I want to apply expressionAttributeValues filter : value #"3" && :value #"1".
How can I do it?
AWSDynamoDBQueryExpression *queryExpression = [AWSDynamoDBQueryExpression new];
queryExpression.exclusiveStartKey = self.queryStartKey;
queryExpression.limit = #500;
queryExpression.indexName = #"st-lud-index";
if( addedDate > 0 )
{
queryExpression.keyConditionExpression = #"st = :value AND lud > :rangeVal";
queryExpression.expressionAttributeValues = #{#":value":#3,#":rangeVal":[NSNumber numberWithDouble:addedDate]};
}
else
{
queryExpression.keyConditionExpression = #"st = :value";
queryExpression.expressionAttributeValues = #{#":value":#3};
}
You can find instructions on how to do that in the Perform a Query section of the following document:
https://docs.aws.amazon.com/aws-mobile/latest/developerguide/add-aws-mobile-nosql-database.html#add-aws-mobile-nosql-database-crud-read
Thanks,
Rohan
Using keyConditionExpression you can query with only one value for the partition key at a time. Assuming st is your partition key, if you need to get two items one with st=3 and another with st=1, you will need to make two separate requests.
However, lud (assuming its your sort key) can use a comparison operator such as <= X or BETWEEN X and Y etc.
Another way to do this is using a scan which will return all items in the table or index. You can use filterExpression to only return those items with st=3 and st=1. Scan is expensive operation so better to call query twice.

Hash holding string arrays doesn't read individual strings in Ruby on Rails

I'm trying to make an array that collects individual strings from other arrays and then creates a hash that counts how many of each string is contained in estimate.bottom. Bottom belongs_to Estimate.
My problem is that it doesn't currently read the individual strings, but the array as a whole. So if the bottoms are ["a", "b"] , ["a"] , and ["b"] the hash bottom_count will be {["a"]=>1, ["b"]=>1, ["a", "b"]=>1} instead of {["a"]=>2, ["b"]=>2}
#in_bottom = []
#estimates.each do |est|
#in_bottom << est.bottom
end
#bottom_count = Hash.new(0)
#in_bottom.each { |in_bottom| #bottom_count[in_bottom] += 1 }
How can I make the method iterate through the individual strings and make bottom_count work correctly?
- #in_bottom.each { |in_bottom| #bottom_count[in_bottom] += 1 }
+ #in_bottom.flatten.each { |in_bottom| #bottom_count[in_bottom] += 1 }
See Documentation Array flatten method

How do you add an item into an array if passes the logical statement?

I would like to create a new array B_array based on an existing array A A_array. If that item in A_array has a certain field then add it into B_array.
Currently this is what I have and its putting everything into B_array:
B_array = A_array.map {|item| if item.name == 'Josh'}
A_array:
[id:0,name:"Josh",email:"josh#josh#gmail.com"],
[id:1,name:"Scott",email:"scott#josh#gmail.com"],
[id:2,name:"Josh",email:"dan#josh#gmail.com"]
Desired output for B_array:
[id:0,name:"Josh",email:"josh#josh#gmail.com"],
[id:2,name:"Josh",email:"dan#josh#gmail.com"]
Thanks!
Use .select:
a = [{id:0,name:"Josh",email:"josh#josh#gmail.com"},
id:1,name:"Scott",email:"scott#josh#gmail.com"}]
b = a.select { |i| i[:name] == 'Josh' }
.select will filter based on a condition you give it and return the array of elements that pass the test.

How to quickly initialise an associative table in Lua?

In Lua, you can create a table the following way :
local t = { 1, 2, 3, 4, 5 }
However, I want to create an associative table, I have to do it the following way :
local t = {}
t['foo'] = 1
t['bar'] = 2
The following gives an error :
local t = { 'foo' = 1, 'bar' = 2 }
Is there a way to do it similarly to my first code snippet ?
The correct way to write this is either
local t = { foo = 1, bar = 2}
Or, if the keys in your table are not legal identifiers:
local t = { ["one key"] = 1, ["another key"] = 2}
i belive it works a bit better and understandable if you look at it like this
local tablename = {["key"]="value",
["key1"]="value",
...}
finding a result with : tablename.key=value
Tables as dictionaries
Tables can also be used to store information which is not indexed
numerically, or sequentially, as with arrays. These storage types are
sometimes called dictionaries, associative arrays, hashes, or mapping
types. We'll use the term dictionary where an element pair has a key
and a value. The key is used to set and retrieve a value associated
with it. Note that just like arrays we can use the table[key] = value
format to insert elements into the table. A key need not be a number,
it can be a string, or for that matter, nearly any other Lua object
(except for nil or 0/0). Let's construct a table with some key-value
pairs in it:
> t = { apple="green", orange="orange", banana="yellow" }
> for k,v in pairs(t) do print(k,v) end
apple green
orange orange
banana yellow
from : http://lua-users.org/wiki/TablesTutorial
To initialize associative array which has string keys matched by string values, you should use
local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};
but not
local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};

Resources