finding list of constant in an array - ruby-on-rails

I have a list of constant:
FRUITS = [MANGO, BANANA, ORANGE, GUAVA]
and array which is superset of this constant, like
EDIBLE_ITEMS = [APPLE, CORN, MANGO, RICE, ORANGE, PAPAYA, LITCHI, RICE]
So now I need to test if any of the elements from FRUITS matches EDIBLE_ITEMS then call a function.
Any help will be appreciated. Thanks

Using Array#&:
FRUITS = ['MANGO', 'BANANA', 'ORANGE', 'GUAVA']
EDIBLE_ITEMS = ['APPLE', 'CORN', 'MANGO', 'RICE', 'ORANGE', 'PAPAYA', 'LITCHI', 'RICE']
(FRUITS & EDIBLE_ITEMS).any?
# => true

Do as below using Enumerable#any? :
EDIBLE_ITEMS = %w[APPLE, CORN, MANGO, RICE, ORANGE, PAPAYA, LITCHI, RICE]
FRUITS = %w[MANGO, BANANA, ORANGE, GUAVA]
FRUITS.any? { |item| EDIBLE_ITEMS.include? item } # => true

Related

How to remove repeated string values from a list

This is a continuation of a previous question.
I have a fixed list in Lua which I am reassigning values for
local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
apple = "RD",
pear = "GR",
orange = "OG",
kiwi = "GR",
tomato = "RD",
banana = "YL",
}
colours = {}
for index = 1, #a do
table.insert(colours,map[a[index]or "OT")
end
Now I would either like to edit the existing script, or add some new script, to remove any repeated values.
My end result should be a table (colours) with no repeated values or empty strings, but I can't seem to think of a neat way to do this!
If it's not possible (or really messy) my second option would be to count the number unique values in the table.
If you don't want to run over the entire table every time you add an element you can simply create a second table where you remember which colours have been listed yet.
Simply use the colour as key.
local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
apple = "RD",
pear = "GR",
orange = "OG",
kiwi = "GR",
tomato = "RD",
banana = "YL",
}
local listedColours = {}
local colours = {}
for _,colour in pairs(a) do
colour = map[colour] or "OT"
if not listedColours[colour] then
table.insert(colours, colour)
listedColors[colour] = true
end
end
Solution i suggest: add to table function contains
table.contains = function(t, value)
for index = 1, #t do
if t[index] == value then
return index
end
end
end
so problem with having only unique colours can be solved like:
for index = 1, #a do
local colour = map[a[index]] or "OT"
if not table.contains(colours, colour) then
table.insert(colours, colour)
end
end
I consider it pretty neat

Extract objects by their properties from list of class names in ruby

I have a list of Class names: obj_list = ["Fruit", "Vegetable"]
and I need to iterate over them and find all object that have color attribute set to red (assuming that both Fruits and vegetables has this attribute).
This sets #fruits with the list of Fruit Objects matching color: 'red' and #vegetables the list of Vegetable Objects matching color: 'red'
obj_list = ["Fruit", "Vegetable"]
obj_list.each do |c|
list_name = "##{c.downcase}s"
list_objects = Object.const_get(c).where(color: 'red')
instance_variable_set(list_name, list_objects)
end
#fruits #=> Fruit.where(color: 'red')
#vegetables #=> Vegetable.where(color: 'red')
hope this helps
You can do it this ways as well:
obj_list = ["Fruit", "Vegetable"]
obj_list.each_with_object(Array.new){ |object, array| array.push(object.constantize.send(:where, {color: 'red'})) }
It will be the array of Active Record relations, containing fruits and vegetables.

Lua string.gsub inside string.gmatch?

I've created this simple example script to output a list of foods. If the food is a fruit then the color of the fruit will be displayed as well. The issue I'm having is in dealing with the irregular pluralization of 'strawberries.'
fruits = {apple = "green", orange = "orange", stawberry = "red"}
foods = {"potatoes", "apples", "strawberries", "carrots", "crab-apples"}
for _, food in ipairs(foods) do
for fruit, fruit_colour in pairs(fruits) do
duplicate = false
if (string.match(food, "^"..fruit) or string.match((string.gsub(food, "ies", "y")), "^"..fruit)) and not(duplicate) then -- this is where the troubles is!
print(food.." = "..fruit_colour)
duplicate = true
break
end
end
if not(duplicate) then
print(food)
end
end
Right now the program outputs:
potatoes
apples = green
strawberries
carrots
crab-apples
What I want is:
potatoes
apples = green
strawberries = red
carrots
crab-apples
I can't figure out why this doesn't work like I want it to!
Well for one thing, you miss-spelled strawberry here:
fruits = {apple = "green", orange = "orange", stawberry = "red"}
You can also work with lua tables as sets, which means that nested loop searching for duplicates is unnecessary. It can be simplified to something like:
fruits = {apple = "green", orange = "orange", strawberry = "red"}
foods = {"potatoes", "apples", "strawberries", "carrots", "crab-apples"}
function singular(word)
return word:gsub("(%a+)ies$", "%1y"):gsub("(%a+)s$", "%1")
end
for _, food in ipairs(foods) do
local single_fruit = singular(food)
if fruits[single_fruit] then
print(food .. " = " .. fruits[single_fruit])
else
print(food)
end
end
stawberry should be strawberry. The loop changes strawberries to strawberry and then tries to match strawberry against ^stawberry, but the typo causes it not to match.

Similar Array items but not exact ruby

I would like to see if I can check 2 arrays with similar values against each other and return the items that are different between the 2. However I have items that have similar names and I would want those to be excluded as well.
Example:
pantry = ["apples", "chedder cheese mild", "flour", "salt"]
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]
#=> desired return ["apples","bacon", "chocolate", "salt"]
What I get using pantry - recipe #=> ["apples", "bacon", "chocolate", "salt", "cheddar cheese mild"]
If we assume that "similar" means multi word strings where all but the last word are the same...
pantry = ["apples", "chedder cheese mild", "flour", "salt"]
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]
result = (pantry + recipe).group_by{|x| x.slice(0,(x.index(/[\s][^\s]+\z/) || x.size))}
result = result.values.select{|x|x.size == 1}.flatten.sort
=> ["apples", "bacon", "chocolate", "salt"]

How can I get the number of instances of a value in a Rails array?

Say I have an array like this:
["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"]
I want to go through the array and create a new array containing each individual color and the amount of times it appeared in the original array.
So, in the new array it would report that "white" appeared 3 times, "blue" appeared 2 times and so on...
How should I go about doing this?
better return a hash...
def arr_times(arr)
arr.inject(Hash.new(0)) { |h,n| h[n] += 1; h }
end
counts = Hash.new(0)
colors.each do |color|
counts[color] += 1
end
result = {}
hash = array.group_by{|item| item}.each{|key, values| result[key] = values.size}
p result
I see you tagged the question with ruby-on-rails.
If this is a database model/column (e.g., User model with color attribute) you should be doing the computation in the DB:
User.count(:all,:group=>:color).sort_by {|arr| -arr[1]}

Resources