Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have an array of objects in which I need to check if it meets a specific criteria.
What I've done is looped through the array and then matched it with the ruby include? object. Problem is I've noticed that there are instances where this causes some codes to return true, when they really should be returning false.
group.plan_codes.each do |code|
normalized_plan_code = code.upcase.gsub(" ", "").gsub("+", "")
normalized_plan_code.include? coverage['plan_description'].upcase.gsub(" ", "").gsub("+", "")
end
I'm basically taking these group.plan_codes and matching them with the coverage['plan_description']. Problem I found was that if the code was something like group plan submitting a code like not group plan would still return true because the group plan is included in the plan description
Would anyone know a better way about doing this? I was thinking it could stop looking after the first element is completed, but am a little caught up on the ruby detect
Use a Regex or a straight equality test (==). For sake of clarity, let's assume (that I'm understanding your question correctly and) that you have an array such as:
plans = [ 'not group plan', 'group plan' ]
and you are trying to find the second element:
including = 'group plan'
plans.detect { |plan| plan.include?(including) }
this returns "not group plan", the first element, because it also includes the string 'group plan'. To remedy that, using regex you could use something like:
plans.detect { |plan| plan.match?(/\A#{Regexp.escape(including)}\z/) }
Now, this returns the second element, because you're looking for an exact match. Since it is an exact match, though, you could also use something simpler:
plans.detect { |plan| plan == including }
What the regex gives you is if each plan can include multiple items:
plans = ['plan a,not group plan,plan b', 'plan a,group plan,plan b']
Which is a comma separated list of plan codes and you're looking for any plan that includes 'group plan', now you can use the regex:
plans.detect { |plan| plan.match?(/,#{Regexp.escape(including)},/) }
and have the second element returned. You'll need to work the regex into a format that works for how you are saving the plan codes (in this example, I chose comma separated list, you might have tabs or semicolons or whatever else. If you have just a white space separated list of codes that can contain whitespace, you need to do more work and reject any items that include any codes that are longer and include the code you're looking for.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to extract the data in my sheet from this huge paragraph. The data behind and after the highlighted data that I need to extract is fixed all the way with no change at all. I guess it can be a guideline.
I tried using Regextract but for some reason it's showing some extra data with the data that I need and I can't seem to use trim to cut it :(
Could you try this implementation I just tested? It should work alright for your purpose.
import re
text = ' 2021-06-09 00:58:49 48s Redz#gmail.com selectedPoliyCode: a8b8a620poliList: {"code":"a8b8a620","isPolicyList":true,"poliyChecked":[{"label":["Audio"],"version":"8","results":[{"results":{"action_audio":"violation"},"area_code":"ALL"}],"description":"Bullying statements in","level":"L1","pt":"ccde764f","categories":["Harassment and bullying"],"poliy":"Bullying statements in","language":"en","isRecommend":false,"checked":true,"pseudo":"","tags":["audio"],"code":"a8b8a620","keywords":["audio"],"content":"<span style=\"background: #ffff00;\">Bull</span>ying statements in NPGA","id":"ccde764f_a8b8a620_en"}]} selectedTitle: Bullying statements;pipeline_infos: {"review_target":"mt_music_report_queue","config_key":"mt_music_report","create_task_logid":"","use_hawk2_config":1,"object_id":"6943268167347227394","env":"prod","object_type":"music_report","create_time":1623166571,"fr_idc":"alisg","mos_extra_data":{}}action: Delete '
pattern_mail = r'(?:\d+s)(.*)(?:selectedPoliyCode)'
pattern_title = r'(?:selectedTitle:)(.*)?;'
pattern_object_id = r'(?:"object_id":")(.*?)(?:")'
mail = re.findall(pattern_mail, text)[0].strip()
title = re.findall(pattern_title, text)[0].strip()
object_id = re.findall(pattern_object_id, text)[0].strip()
Note that the text is the one you posted in the spreadsheet. Also, the pattern for mail might be "selectedPolicyCode".
The three variables should contain the desired values.
My solution is in python, but the regex should work the same. Let me know if it works.
mail: (?:\d+s)(.)(?:selectedPoliyCode)
title: (?:selectedTitle:)(.)?;
id: (?:"object_id":")(.*?)(?:")
Here you can find them used in the black row of words (formula is there):
https://docs.google.com/spreadsheets/d/1m7Z9R1KKwcvGN0K_2TwOO19KsehfDWIcxoL9potYG7M/edit?usp=sharing
mail: =REGEXEXTRACT(B5, "(?:\d+s)(.*)(?:selectedPoliyCode)")
title: =REGEXEXTRACT(B5, "(?:selectedTitle:)(.*)?;")
id: =REGEXEXTRACT(B5, "(?:""object_id"":"")(.*?)(?:"")")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on ruby on rails project and I want to match specific substring with string suppose part1_hello_part2,part3_hii_part4 this is 2 strings and I want to match with the substring _hello_
Items array:
[
{
id:1,
name:part1_hello_part2,
},{
id:2,
name:part3_hii_part4,
}
...
...
{
}
]
for item in #items
if item.name.to_s.match? /\b.*?_hello_.*?\b/
#data.push item
end
end
In the loop of items, I have strings with the name field if match with a specific substring then item push in the data variable. how can I do this?
Update: Actually I want to push the matched data(*_hello_*) in new array #data so I use that in another process
It's not clear what #items is. If it's an ActiveRecord::Relation, then you probably just want to use a query. If it's some other enumerable, like an Array...
item in #items isn't very rubyish, so you might consider:
#items.each do |item|
if item.name.to_s.match? /\b.*?_hello_.*?\b/
#data.push item
end
end
But, #data.push suggests you're building an array, so you might consider:
#data = #items.each_with_object([]) do |item, to_return|
if item.name.to_s.match? /\b.*?_hello_.*?\b/
to_return.push item
end
end
But, each_with_object is a long walk when you have select, so you might consider:
#data = #items.select do |item|
item.name.to_s.match? /\b.*?_hello_.*?\b/
end
Now, you also have include?, so you might consider:
#data = #items.select do |item|
item.name.to_s.include?('_hello_')
end
At that point, you might want to get it all onto one line, so you might consider:
#data = #items.select { |item| item.name.to_s.include?('_hello_')}
You might want to compact that a little more, so you might consider:
#data = #items.select { |item| item.name.to_s['_hello_'] }
As you have probably tried out already by yourself using irb,
'part1_hello_part2'.match? /\b.*?_hello_.*?\b/
returns true, so the problem is not the matching part (although you probably should have written it better as .include?('_hello_'), which looks - at least to me - simpler and easier to understand than your obscure regexp.
If the matching does not work, it means that the left side is not the string what you expect it to be. At the very least, you should output item.name.to_s for debugging purposes. You did not show what #items is. You only said that it is an Array and show a printed representation of its content, which is not the same as showing what the content really is. From the display, it looks like the array elements were hashes, but in this case, I would expect that the elements were accessed by item[:name]. But if ìtemis not just a Hash, but an object which understands the name` method, this is, of course, a correct usage.
Aside from this, and assuming that #data understands the method push, your code looks fine, and you need to ask more precisely, which of the statements you have posted, does not yield the expected outcome.
Im having issues with rails with the code
if #turno.chop == res[:department].to_s
where turno contains strings like ABC1 and department like ABC, im trying to filter if turno its equal of department but i need reduce the string of turno for that.
Every time what i try to do that the code dont finish and stuck in other part of code, when i delete the condition, the code works perfectly but dont do the filter.
i tryid to to do like
if #turno.include?(res[:department].to_s)
But appears the same error.
I believe something very similar to this was answered in the stackoverflow.com question. How to check whether a string contains a substring in Ruby?
The include? command sounds like what you should use.
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
To be more accurate, #turno can contain a string like "ABC1" and res[:department] contains a string with "ABC" i need reduce the string in #turno to the first X characters and compare it with the content of res[:department]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Trying to add the contents of an array together.
["75.00", "50.00", "25.00"] the way I'm getting that info is with
c = Credit.last
c.payments.map(&:payment_amount).to_a
I'm trying to add up all the values together in the array.
The other posters are correct in that your question doesn't conform to the how to ask guidelines. The responses are not intended to put you down but rather to maintain the quality of content for stack overflow. That said this should get you where you need to go. IN the future please read the guidelines and submit accordingly.
Credit.last.payments.sum(:payment_amount.to_f)
One thing you may not have considered is that the array ["75.00", "50.00", "25.00"] contains a bunch of strings.
If you were to sum them together like this:
["75.00", "50.00", "25.00"].sum
# or like this as one commenter suggested
["75.00", "50.00", "25.00"].reduce(&:+)
# or the long-handed version
["75.00", "50.00", "25.00"].reduce {|str, val| str + val }
You would actually get "75.0050.0025.00". This is because the individual strings in the array are getting concatenated together.
So in fact, you would need to convert the array to floats or integers first. This can be done like this:
floats = ["75.00", "50.00", "25.00"].collect(&:to_f)
# or the long-handed version
["75.00", "50.00", "25.00"].collect {|val| val.to_f }
Then you can sum the values:
sum = floats.sum
Edit:
I just tried summing a string column via ActiveRecord and got an exception ActiveRecord::StatementInvalid: TinyTds::Error: Operand data type nvarchar is invalid for sum operator.:.
payment_total = Credit.last.payments.sum(:payment_amount)
# returns ActiveRecord::StatementInvalid:
# TinyTds::Error: Operand data type nvarchar is invalid for sum
# operator.
Looks like that won't be an option for you. Although, you could change the datatype of the column so that it is something other than a string. If you change the column datatype then you will be able to use aggregate functions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I find record without id?
This doesn't work
Wallet wallet = db.Wallet.Where(n => n.Name == My.Name && n.UserId == userId);
This works fine
Wallet wallet = db.Wallet.Find();
Linq queries can return multiple results, and you can't assign an IEnumerable<Wallet> when you've only allocated space for a single Wallet. If you only want one result, you should use an appropriate method to narrow it down.
Single
Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
SingleOrDefault.
Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
First
Returns the first element of a sequence.
FirstOrDefault
Returns the first element of a sequence, or a default value if the sequence contains no elements.
As an example:
Wallet wallet = db.Wallet.Where(n => n.Name == My.Name && n.UserId == userId).Single();
Always compare the return type of your Linq query to what you're trying to assign it to. Intellisense in Visual Studio will help you with that.
Note these methods all have overloads that make the use of "Where" unnecessary, you can put the filter lambda directly in the call, as in:
Wallet wallet = db.Wallet.Single(n => n.Name == My.Name && n.UserId == userId);
Which style you use is up to you, based on which you think is more readable. The performance difference is probably negligible (though it might be worth it to test).