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]
Related
I am trying to apply the following regex to one of my views:
^([^\s]+)\s+
This is to remove any string of consecutive non-whitespace characters including any white space characters that follow from the start of the line (remove everything except the first word). I have input it on Rubular and it works.
I was wondering how I would be able to apply it to my rails project. Would I create a rails helper method? So far I have tested it in irb and it is not returning the right value:
I would like to know how I can fix my method and if making it a helper method is the right approach. Thank you very much for your help guys!
The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.
You could either try it with String.match and work with the match data.
like
str.match(^([^\s]+)\s+)
or you don't use regex for readability. Split the string on spaces and return and array of the words and take the first one, like:
str.split(' ').first
I'm going to preface that I'm still learning ruby.
I'm writing a script to parse a .csv and identify possible duplicate records in the data-set.
I have a .csv file with headers, so I'm parsing the data so that I can access each row using a header title as such:
#contact_table = CSV.parse(File.read("app/data/file.csv"), headers: true)
# Prints all last names in table
puts contact_table['last_name']
I'm trying to iterate over each row in the table and identify if the last name I'm currently iterating over is similar to the next last name, but I'm having trouble doing this. I guess the way I'm handling it is as if it's an array, but I checked the type and it's a CSV::Row.
example (this doesn't work):
#contact_table.each_with_index do |c, i|
puts "first contact is #{c['last_name']}, second contact is #{c[i + 1]['last_name']}"
end
I realized this doesn't work like this because the table isn't an array, it's a CSV::Row like I previously mentioned. Is there any method that can achieve this? I'm really blanking right now.
My csv looks something like this:
id,first_name,last_name,company,email,address1,address2,zip,city,state_long,state,phone
1,Donalt,Canter,Gottlieb Group,dcanter0#nydailynews.com,9 Homewood Alley,,50335,Des Moines,Iowa,IA,515-601-4495
2,Daphene,McArthur,"West, Schimmel and Rath",dmcarthur1#twitter.com,43 Grover Parkway,,30311,Atlanta,Georgia,GA,770-271-7837
#contact_table should be a CSV::Table which is a collection of CSV::Rows so in this:
#contact_table.each_with_index do |c, i|
...
end
c is a CSV::Row. That's why c['last_name'] works. The problem is that here:
c[i + 1]['last_name']
you're looking at c (a single row) instead of #contact_table, if you said:
#contact_table[i + 1]['last_name']
then you'd get the next last name or, when c is the last row, an exception because #contact_table[i+1] will be nil.
Also, inside the iteration, c is the current (or (i+1)th) row and won't always be the first.
What is your use case for this? Seems like a school project?
I recommend for_each instead of parse (see this comparison). I would probably use a Set for this.
Create a Set outside of the scope of parsing the file (i.e., above the parsing code). Let's call it rows.
Call rows.include?(row) during each iteration while parsing the file
If true, then you know you have a duplicate
If false, then call rows.add(row) to add the new row to the set
You could also just fill your set with an individual value from a column that must be distinct (e.g., row.field(:some_column_name)), such as email or phone number, and do the same inclusion check for that.
(If this is for a real app, please don't do this. Use model validations instead.)
I would use #read instead of #parse and do something like this:
require 'csv'
LASTNAME_INDEX = 2
data = CSV.read('data.csv')
data[1..-1].each_with_index do |row, index|
puts "Contact number #{index + 1} has the following last name : #{row[LASTNAME_INDEX]}"
end
#~> Contact number 1 has the following last name : Canter
#~> Contact number 2 has the following last name : McArthur
I am currently using this formula to get all the data from everyone whose first name is "Peter", but my problem is that if someone is called "Simon Peter" this data is gonna show up on the formula output.
=QUERY('Data'!1:1000,"select * where B contains 'Peter'")
I know that for the other formulas if I add an * to the String this issue is resolved. But in this situation for the QUERY formula the same logic do not applies.
Do someone knows the correct syntax or a workaround?
How about classic SQL syntax
=QUERY('Data'!1:1000,"select * where B like 'Peter %'")
The LIKE keyword allows use of wildcard % to represent characters relative to the known parts of the searched string.
See the query reference: developers.google.com/chart/interactive/docs/querylanguage You could split firstname and lastname into separate columns, then only search for firstnames exactly equal to 'Peter'. Though you may want to also check if lowercase/uppercase where lower(B) contains 'peter' or whitespaces are present in unexpected places (e.g., trim()). You could also search only for values that start with Peter by using starts with instead of contains, or a regular expression using matches. – Brian D
It seems that for my case using 'starts with' is a perfect fit. Thank you!
I have a GrapeSwaggerRails API application that takes a two dates and a comma-delimited string of category IDs. It should query the database for Records with a created_at within the two given dates and a category_id that matches one of the IDs passed to it. I'm not having any trouble with the dates, so I'll skip that for now. But let's say I want Records with categories matching 8, 2, or 1. In the code, it looks like "8,2,1". In the URL, it gets appended as &categories=%228%2C2%2C1%22.
Anyway, I figured one decent way of getting this to do what I want would be to convert that string into an array of integers like this: categories = params[:categories].split(',').map(&:to_i)
But given "8,2,1", the output is this (ignore the comment):
0 # <-- ?????
2
1
Very strange. In the definition of the API, params[:categories] looks like this: "8,2,1". But params[:categories].split(',') becomes the following:
"8
2
1"
That's a bit odd, isn't it? Running the map method on that turns it into that nonsense higher up, converting the "8 to a 0 for reasons I'm hoping to find out here. I know I could probably come at this problem from a different angle and sidestep the issue, but I'd rather try to get to the root of what's going wrong, so I can learn something from it. For reference, here's what the Rails console does when I put (as far as I can tell) the same data into it:
>> "8,2,1".split(',')
#=> ["8", "2", "1"]
map then works as expected.
>> "8,2,1".split(',').map(&:to_i)
#=> [8, 2, 1]
So my question is twofold. What's going wrong with this split function? Why does it behave differently in the console?
Because params[:categories] is actually
'"8,2,1"' # <- the outer ''s are just for illustration of a string.
If you pass &categories=8%2C2%2C1 it should work as expected.
No matter what language I'm using I always need to display a list of strings separated by some delimiter.
Let's say, I have a collection of products and need to display its names separated by ', '.
So I have a collection of Products, where each one has a 'name' attribute. I'm looking for some Rails method/helper (if it doesn't exist, maybe you can give me ideas to build it in a rails way) that will receive a collection, an attribute/method that will be called on each collection item and a string for the separator.
But I want something that does not include the separator at the end, because I will end with "Notebook, Computer, Keyboard, Mouse, " that 2 last characters should not be there.
Ex:
concat_ws(#products, :title, ", ")
#displays: Notebook, Computer, Keyboard, Mouse
Supposing #products has 4 products with that names of course.
Thanks!
you should try the helper to_sentence.
If you have an array, you can do something like
array.to_sentence. If your array has the data banana, apple, chocolate it will become:
banana, apple and chocolate.
So now if you have your AR Model with a field named, you could do something like
MyModel.all.map { |r| r.name }.to_sentence
#products.map(&:title).join(', ')
As #VP mentioned, Array#to_sentence does this job well in rails. The code for it is here:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/conversions.rb
Saying that, its use of the Oxford Comma is questionable :-)