Finding common string in array of strings (ruby)
Here's a rubyish way of doing it. You should use a more advanced algorithm if you have a bunch of strings or they are very long, though:
def longest_common_substr(strings)
shortest = strings.min_by &:length
maxlen = shortest.length
maxlen.downto(0) do |len|
0.upto(maxlen - len) do |start|
substr = shortest[start,len]
return substr if strings.all?{|str| str.include? substr }
end
end
end
puts longest_common_substr(["Extra tv in bedroom",
"Extra tv in living room",
"Extra tv outside the shop"])
Find most common string in an array
Ruby < 2.2
#!/usr/bin/ruby1.8
def most_common_value(a)
a.group_by do |e|
e
end.values.max_by(&:size).first
end
x = ["1.111", "1.122", "1.250", "1.111"]
p most_common_value(x) # => "1.111"
Note: Enumberable.max_by
is new with Ruby 1.9, but it has been backported to 1.8.7
Ruby >= 2.2
Ruby 2.2 introduces the Object#itself method, with which we can make the code more concise:
def most_common_value(a)
a.group_by(&:itself).values.max_by(&:size).first
end
As a monkey patch
Or as Enumerable#mode
:
Enumerable.class_eval do
def mode
group_by do |e|
e
end.values.max_by(&:size).first
end
end
["1.111", "1.122", "1.250", "1.111"].mode
# => "1.111"
All Common Subsequences in Array of Strings
Well, these smaller subsequences like "a" and "aa" are common subsequences, so that wouldn't be incorrect.
If you really only want the longest common subsequences (i.e. those subsequences not contained in any other common subsequence), what you need to do is to check whether these subsequences are part of the larger common subsequence, and if so, discard them.
This can be done by (in pseudocode)
finalsubsequences = copy(subsequences);
for(subseq in subsequences) {
for(subseq2 in subsequences) {
if(subseq2.indexOf(subseq) != false)
// subseq contains subseq2, thus discard subseq2
finalsubsequences.remove(subseq2);
}
}
Good luck!
Check if string contains any substring in an array in Ruby
I think we can divide this question in two:
- How to clean undesired data
- How to check if cleaned data is valid
The first is well answered above. For the second, I would do the following:
(cleaned_content_types - VALID_CONTENT_TYPES) == 0
The nice thing about this solution is that you can easily create a variable to store the undesired types to list them later like this example:
VALID_CONTENT_TYPES = ['image/jpeg']
cleaned_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/jpeg']
undesired_types = cleaned_content_types - VALID_CONTENT_TYPES
if undesired_types.size > 0
error_message = "The types #{undesired_types.join(', ')} are not allowed"
else
# The happy path here
end
String substitution within ruby array
This should do it:
@tickets = Ticket.where(active: true).
pluck(
:door_manufacturer,
:job_number,
:door_style,
:door_allocation_date,
:date_doors_received_in_aub,
:door_delivery_due_date,
:notes
).map { |ticket| ticket.map(&:to_s) }
Ruby get strings from array which contain substring
You are almost there, you cannot pass parameter in &:
. You can do something like:
o.select{ |e| e.include? 'c' }
Efficient way (in Ruby), to determine largest matching sequence in an array/string?
Here's a fast working solution, cutting down the comparison to only those element in common across arrays:
array1 = ["hello", "world", "i", "am", "in", "the", "world"]
array2 = ["This", "is", "the", "hello", "world", "message"]
common_words = array1 & array2
stringified_array1 = array1.join(' ')
stringified_array2 = array2.join(' ')
(common_words.length - 1).downto(0).map do |n|
stringified_combo = array1[0..n].join(' ')
if stringified_array1.include?(stringified_combo) && stringified_array2.include?(stringified_combo)
stringified_combo.split($,)
end
end.compact.max
This you get the words in common between the two arrays, and tests these from largest to smallest. You check they're in order in the first array, then if they exist in the second.
I believe this holds up and is pretty efficient, though happy to receive any comments and feedback,
Ruby - Count the number of strings in an array that contain either of two characters
a.group_by { |e| e[-1] }.each_with_object({}) { |(k, v), hash| hash[k] = v.count }
#=> {"D"=>20, "M"=>7}
Steps:
groups = a.group_by { |e| e[-1] }
# {
# "D"=> ["P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P1 - D", "P2 - D", "P2 - D", "P2 - D", "P3 - D", "P3 - D", "P - D", "P - D", "P - D", "Post - D", "S1 - D"],
# "M"=> ["P3 - M", "P1 - M", "P1 - M", "P2 - M", "P2 - M", "P1 - M", "P1 - M"]
# }
group_counts = groups.each_with_object({}) { |(k, v), hash| hash[k] = v.count }
#=> {"D"=>20, "M"=>7}
group_counts['M']
#=> 20
edit
With Ruby 2.4+ you can make use of Hash#transform_values
(credits go to Alex Golubenko :)):
a.group_by { |e| e[-1] }.transform_values(&:size)
#=> {"D"=>20, "M"=>7}
Related Topics
How to Run Rake with --Trace Within Capistrano
Ruby Incorrectly Parses 2 Digit Year
Configure Webrick to Use Automatically Generated Self-Signed Ssl/Https Certificate
How to Extend Redcarpet to Support Auto Linking User Mentions
Converting an Array of Hashes to One Hash in Ruby
Extract All Urls Inside a String in Ruby
How to Source Environment Variables for a Command Shell in a Ruby Script
How to Add New View to Ruby on Rails Spree Commerce App
Ruby on Rails Country/State Select Enigma
Authlogic Perishable_Token Resets on Every Request
Ruby Variable as Same Object (Pointers)
How to Create a Charge and a Customer in Stripe (Rails)
Ruby on Rails: Search Form - Multiple Search Fields
JSON::Parsererror: 757: Unexpected Token at '{
Custom_Require.Rb:36:In 'Require': No Such File to Load -- Myapp(Loaderror)
How to Run "Bundle Exec Jekyll New ."
Ruby Convert Idn Domain from Punycode to Unicode
How to Require File from 'Gem' Which Are Not Under 'Lib' Directory