Return string from multiple array items - ruby-on-rails

I have multiple arrays which have code string items in them. I need to match the code from a given string and then return a class name from the matched array.
Might be better if I show you what I've got. So below are the arrays and underneath this is the string I need to return if the given string matches an item from within the array. So lets say I send a string of '329' this should return 'ss4' as a string:
['392', '227', '179', '176']
= 'ss1'
['389', '386']
= 'ss2'
['371', '338', '335']
= 'ss3'
['368', '350', '332', '329', '323', '185', '182']
= 'ss4'
I need to know what would be the best approach for this. I could create a helper method and have an array for each code block and then check each array to see if the given string code is contained and then return the string, which could be ss1 or ss4. Is this a good idea?

The most efficient approach would be to generate a translator hash once that can perform the lookup super fast:
CODES = {
ss1: ['392', '227', '179', '176'],
ss2: ['389', '386'],
ss3: ['371', '338', '335'],
ss4: ['368', '350', '332', '329', '323', '185', '182']
}
translator = CODES.each_with_object({}){|(s, a), m| a.each{|n| m[n] = s.to_s}}
Now you can simply do:
translator['329']
=> "ss4"
translator['389']
=> "ss2"

def code_to_string(code)
if [395].include? code
"ss1"
elsif [392, 227, 179, 176].include? code
"ss2"
# and so on
end
Note that the codes are integers. to match with a string code, use %w(392 227 179).include? instead of the array

Here's one solution you could try:
CODE_LOOKUP = {
[395] => 'ss1',
[392, 227, 179, 176] => 'ss2',
[389, 386] => 'ss3'
# etc
}
def lookup_code(code)
CODE_LOOKUP.each do |codes_to_test, result|
return result if codes_to_test.include?(code)
end
end
lookup_code(395)
# => "ss1"
lookup_code(179)
# => "ss2"

h = {:ss1 => [395],:ss2 => [392, 227, 179, 176] }
h.key(h.values.find{|x| x.include? "392".to_i})
#=> :ss2

I'd recommend joining all the arrays into a multi-dimensional hash and then searching that.
a1 = ['395']
a2 = ['392', '227', '179', '176']
h = { a1: a1, a2: a2 }
h.select {|a, v| a if v.include?('392') }.keys.first.to_s

Related

Need help assigning values to a new array then calculating those values

def solve(c)
letter_values =('a'..'z').map.with_index(1) {|letter,value| [letter,value] }
remove_vowels =c.gsub(/[aeiou]/, ' ').split()
end
solve("zodiacs")
The letter_values array has the alphabet letters with numbers. I need to assign those numbers to the remove_vowels variable, which should only return consonants to carry out a calculation later on. If "z" is return, I need to look in the array and take the value of "z" which is 26 and assign it as a value to z from the regex.
So you want the index in the alphabet of each letter?
See this post
letter_values = ('a'..'z').map do |l| l.bytes.first - 96 end
def solve(c)
letter_values =('a'..'z').map.with_index(1) { |letter,value| [letter,value] }.to_h
remove_vowels = c.gsub(/[aeiou]/, '').split('')
hash = Hash.new
remove_vowels.map { | consonants | hash[consonants] = letter_values[consonants]}
hash
end
solve("zodiacs") => this will return {"z"=>26, "d"=>4, "c"=>3, "s"=>19}
Or you could use #each_with_object, the result will be the same; it cleans the code up quite a bit:
def solve(c)
letter_values =('a'..'z').map.with_index(1) { |letter,value| [letter,value] }.to_h
remove_vowels = c.gsub(/[aeiou]/, '').split('')
remove_vowels.each_with_object({}) { |constanant, hash| hash[constanant] = letter_values[constanant]}
end
solve("zodiacs") => this will return {"z"=>26, "d"=>4, "c"=>3, "s"=>19}

How to format data Rails

I need to retrieve data from database column and put them to
[{1442507641,1},{1442507642,2},{1442507643,3},{1442507644,4}...]
format as the plot format requires.
I'm trying to do this by :
#data = TableName.where(:id => requiredid)
.map {|r| { r.received_date.to_i => r.value } }
but this returns format
data=[{1442507641=>6}, {1442507641=>7}, {1442507641=>5}, {1442507641=>6}, {1442507641=>5}, {1442507695=>9}, {1442507695=>9}, {1442507695=>7}, {1442507695=>8}]
How can I make the bracket as plot requires and remove the strange =&gt ?
It seems like this ought to do what you're asking for:
parts = TableName.where(:id => requiredid).map do |r|
sprintf("{%d,%d}", r.received_date, r.value)
end
#data = "[#{parts.join(",")}]"
It's only for your options to manipulate your data:
#data = []
#data = User.where(:id => requiredid).map {|r| #data << "{#{r. received_date}, #{r.value}}"}
First you make #data as array. Than collect the string into array.

Ruby way to group anagrams in string array

I implemented a function to group anagrams.
In a nutshell:
input: ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', scream']
output: [["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]]
I would like to know if there is a better way to do this.
I really think I used too much repetition statements: until, select,
delete_if.
Is there any way to combine the select and delete_if statement? That
means, can selected items be automatically deleted?
Code:
def group_anagrams(words)
array = []
until words.empty?
word = words.first
array.push( words.select { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )
words.delete_if { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) }
end
array
end
Thanks in advance,
Like that:
a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']
a.group_by { |element| element.downcase.chars.sort }.values
Output is:
[["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
If you want to you can turn this one-liner to a method of course.
You could use the partition function instead of select, implemented in Enumerable. It splits the entries within the array according to the decision-function into two arrays.
def group_anagrams(words)
array = []
until words.empty?
word = words.first
delta, words = words.partition { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )
array += delta
end
array
end
(untested)

Ruby on Rails: Array to Hash with (key, array of values)

Lets say I have an Array of content_categories (content_categories = user.content_categories)
I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set
In PHP something like this is possible:
foreach ($content_categories as $key => $category) {
$contentsByCategoryIDArray = Category.getContents($category[id])
$content_categories[$key][$contentsByCategoryIDArray]
}
Is there an easy way in rails to do this?
Greets,
Nico
Your question isn't really a Rails question, it's a general Ruby programming question.
Your description isn't very clear, but from what I understand, you want to group IDs for common categories using a Hash. There are various other ways of doing this, but this is easy to understand::
ary = [
'cat1', {:id => 1},
'cat2', {:id => 2},
'cat1', {:id => 3}
]
hsh = {}
ary.each_slice(2) { |a|
key,category = a
hsh[key] ? hsh[key] << category[:id] : hsh[key] = [category[:id]]
}
hsh # => {"cat1"=>[1, 3], "cat2"=>[2]}
I'm using a simple Array with a category, followed by a simple hash representing some object instance, because it makes it easy to visualize. If you have a more complex object, replace the hash entries with those objects, and tweak how you access the ID in the ternary (?:) line.
Using Enumerable.inject():
hsh = ary.each_slice(2).inject({}) { |h,a|
key,category = a
h[key] ? h[key] << category[:id] : h[key] = [category[:id]]
h
}
hsh # => {"cat1"=>[1, 3], "cat2"=>[2]}
Enumerable.group_by() could probably shrink it even more, but my brain is fading.
I'd use Enumerable#inject
content_categories = content_categories_array.inject({}){ |memo, category| memo[category] = Category.get_contents(category); memo }
Hash[content_categories.map{|cat|
[cat, Category.get_contents(cat)]
}]
Not really the right answer, because you want IDs in your array, but I post it anyway, because it's nice and short, and you might actually get away with it:
content_categories.group_by(&:category)
content_categories.each do |k,v|
content_categories[k] = Category.getContents(v)
end
I suppose it's works
If i understand correctly, content_categories is an array of categories, which needs to be turned into a hash of categories, and their elements.
content_categories_array = content_categories
content_categories_hash = {}
content_categories_array.each do |category|
content_categories_hash[category] = Category.get_contents(category)
end
content_categories = content_categories_hash
That is the long version, which you can also write like
content_categories = {}.tap do |hash|
content_categories.each { |category| hash[category] = Category.get_contents(category) }
end
For this solution, content_categories must be a hash, not an array as you describe. Otherwise not sure where you're getting the key.
contents_by_categories = Hash[*content_categories.map{|k, v| [k, Category.getContents(v.id)]}]

returning an array that contains an array and hash in ruby method?

HI
is it possible to return an array that contains an array and hash from a method in ruby?
i.e
def something
array_new = [another_thing, another_thing_2]
hash_map = get_hash()
return [array_new, hash_map]
end
and to retrieve the array:
some_array, some_hash = something()
thanks
Sure, that's perfectly possible and works exactly as in your example.
You will only ever be able to return one thing. What you are returning there is an array containing an array and a hash.
Ruby methods can be treated as if they return multiple values so you can collect the items in an array or return them as separate objects.
def something
array_new = Array.new
hash_new = Hash.new
return array_new, hash_new
end
a, b = something
a.class # Array
b.class # Hash
c = something
c.class # Array

Resources