Ruby CSV Conversion Error - ruby-on-rails

I am simply trying to get the average two columns of a colon separated file. What am I doing wrong here?
/experimental/1$ cat list.csv
a:7:98:East
b:2:34:East
c:10:94:North
d:7:43:West
e:6:88:South
/experimental/1$ cat play.rb
#!/usr/bin/env ruby
require 'csv'
average_spending = Array.new
CSV.foreach('list.csv', converters: :numeric, { :col_sep => ':' }) do |row|
average_spending << row[2] / row[1]
end
/experimental/1$ ./play.rb
./play.rb:5: syntax error, unexpected ')', expecting tASSOC
... :numeric, { :col_sep => ':' }) do |row|
... ^
./play.rb:7: syntax error, unexpected keyword_end, expecting $end
Thank you in advance,
~Chris

CSV.foreach accepts 2 arguments and block(you are trying to pass 3), use
CSV.foreach('list.csv', { converters: :numeric, col_sep: ':' }) {...}

Related

Ruby default values error

I was reading the source code of a gem "activerecord-postgres-earthdistance".
While running the migration script, it threw an error on the following method
def order_by_distance lat, lng, order: "ASC"
It gave an error for order: "ASC"
syntax error, unexpected tLABEL
Isn't this valid Ruby syntax?
Ruby 2.0 supports keywords arguments
[5] pry(main)> def bar(a: "name", b: "fem"); puts a,b end
[6] pry(main)> bar(a: "John", b: "Male")
John
Male
[7] pry(main)> bar("John", "Male")
ArgumentError: wrong number of arguments (2 for 0)
from (pry):5:in `bar'
However the above is not valid in 1.9 see below:
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]
[2] pry(main)> def bar(a: "name", b: "fem"); puts a,b end
SyntaxError: unexpected ',', expecting $end
def bar(a: "name", b: "fem"); puts a,b end
^
[2] pry(main)> def bar(a: "name"); puts a end
SyntaxError: unexpected ')', expecting $end
def bar(a: "name"); puts a end
^
For better understanding you can read here and here
def order_by_distance(lat, lng, hash={})
puts hash[:order]
end
=> order_by_distance(lat, lng, order: "ASC")
=> "ASC"
use hash arguments in ruby

syntax error, unexpected ',', expecting tCOLON2 or '[' or '.' when assigning a class to erb

In my profile.html.erb file I get a syntax error anytime I try to assign a class or id to erb. Below is an example:
<p>"<%= current_user.current_program.name, :id => 'progress' %>" Progress</p>
This gives me the following error:
SyntaxError in Users#profile
Showing /.../app/views/users/profile.html.erb where line #13 raised:
/Users/.../app/views/users/profile.html.erb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
...er.current_program.name, :id => 'progress' );#output_buffer....
... ^
I can't figure out what the syntax error is. I'm totally stumped.
We can reproduce and simplify your problem in a standalone Ruby like so:
require 'erb'
ERB.new("<p><%= name, :a => 'b' %></p>").run
Producing the error:
SyntaxError: (erb):1: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
..."; _erbout.concat(( name, :a => 'b' ).to_s); _erbout.concat ...
... ^
from /Users/phrogz/.../ruby/1.9.1/erb.rb:838:in `eval'
from /Users/phrogz/.../ruby/1.9.1/erb.rb:838:in `result'
from /Users/phrogz/.../ruby/1.9.1/erb.rb:820:in `run'
from (irb):2
from /Users/phrogz/.../bin/irb:16:in `<main>'
Even more simply, taking ERB out of the mix:
a, :b=>'c'
#=> SyntaxError: (irb):3: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
What you have just isn't valid Ruby code. What were you trying to do there? Pass the :id => 'progress' hash as a parameter to the .name method? If so, then drop the comma, and (optionally) include parentheses for clarity:
<p>"<%= current_user.current_program.name( :id=>'progress' ) %>" Progress</p>
And if you're using Ruby 1.9+, you can use the simpler Hash-with-symbol-keys syntax:
<p>"<%= current_user.current_program.name( id:'progress' ) %>" Progress</p>
However, it seems unlikely to me that the name method takes such a hash, so I ask again: what are you really trying to accomplish? What does the name method return, and what HTML output do you want?
Taking a guess, maybe you wanted the text returned by .name to be wrapped in <span id="progress">? If so, you must do so like:
<p>"<span id="progress"><%= current_user.current_program.name%></span>" Progress</p>
Or perhaps using content_tag:
<p><%= content_tag("span", current_user.current_program.name, id:'progress') %> Progress</p>
In Haml this would be:
%p
%span#progress= current_user.current_program.name
Progress
maybe if you remove the comma it will work (is current_user.current_program.name a method that takes a hash as a parameter?)

Error parsing CSV with FasterCSV gem (MalformedCSVError)

FasterCSV is raising MalformedCSVError (Illegal Quoting) in this line:
|0150|1161623|Medicamentos e genericos "EPP".|1423|PB|
This is the code:
FasterCSV.foreach(path_to_file, :col_sep => '|') do |row|
...
end
Any ideas?
tks!!
There is also an option quote_char which defaults to ", try changing it to something, which you don't expect in your data. You might try nil but I have never tried that.
FasterCSV.foreach(path_to_file, :col_sep => '|', :quote_char => "|") do |row|
...
end

How to change the encoding during CSV parsing in Rails

I would like to know how can I change the encoding of my CSV file when I import it and parse it. I have this code:
csv = CSV.parse(output, :headers => true, :col_sep => ";")
csv.each do |row|
row = row.to_hash.with_indifferent_access
insert_data_method(row)
end
When I read my file, I get this error:
Encoding::CompatibilityError in FileImportingController#load_file
incompatible character encodings: ASCII-8BIT and UTF-8
I read about row.force_encoding('utf-8') but it does not work:
NoMethodError in FileImportingController#load_file
undefined method `force_encoding' for #<ActiveSupport::HashWithIndifferentAccess:0x2905ad0>
Thanks.
I had to read CSV files encoded in ISO-8859-1.
Doing the documented
CSV.foreach(filename, encoding:'iso-8859-1:utf-8', col_sep: ';', headers: true) do |row|
threw the exception
ArgumentError: invalid byte sequence in UTF-8
from csv.rb:2027:in '=~'
from csv.rb:2027:in 'init_separators'
from csv.rb:1570:in 'initialize'
from csv.rb:1335:in 'new'
from csv.rb:1335:in 'open'
from csv.rb:1201:in 'foreach'
so I ended up reading the file and converting it to UTF-8 while reading, then parsing the string:
CSV.parse(File.open(filename, 'r:iso-8859-1:utf-8'){|f| f.read}, col_sep: ';', headers: true, header_converters: :symbol) do |row|
pp row
end
force_encoding is meant to be run on a string, but it looks like you're calling it on a hash. You could say:
output.force_encoding('utf-8')
csv = CSV.parse(output, :headers => true, :col_sep => ";")
...
Hey I wrote a little blog post about what I did, but it's slightly more verbose than what's already been posted. For whatever reason, I couldn't get those solutions to work and this did.
This gist is that I simply replace (or in my case, remove) the invalid/undefined characters in my file then rewrite it. I used this method to convert the files:
def convert_to_utf8_encoding(original_file)
original_string = original_file.read
final_string = original_string.encode(invalid: :replace, undef: :replace, replace: '') #If you'd rather invalid characters be replaced with something else, do so here.
final_file = Tempfile.new('import') #No need to save a real File
final_file.write(final_string)
final_file.close #Don't forget me
final_file
end
Hope this helps.
Edit: No destination encoding is specified here because encode assumes that you're encoding to your default encoding which for most Rails applications is UTF-8 (I believe)

Syntax errors in html file

Not exactly sure what the errors are indicating. I am getting the following syntax errors:
compile error
app/views/students/student_fail.html.haml:33: syntax error, unexpected tIDENTIFIER, expecting ')'
... :student_fail_attribute params[:StudentFailState.true], pa...
^
app/views/students/student_fail.html.haml:33: syntax error, unexpected ')', expecting '='
...method], params[:text_method])
^
app/views/students/student_fail.html.haml:39: syntax error, unexpected kENSURE, expecting kEND
...\n", -2, false);_erbout;ensure;#haml_buffer = #haml_buffer.u...
^
app/views/students/student_fail.html.haml:40: syntax error, unexpected kENSURE, expecting kEND
app/views/students/student_fail.html.haml:42: syntax error, unexpected $end, expecting kEND
Here's the html:
:ruby
fields = if #step == 1
[ select_tag(:id, options_from_collection_for_select(Student.passed, :id, :selector_label, #student.id), :size => 10) ]
elsif #step == 2
form_for #student do |f| f.collection_select( :student_fail_attribute params[:StudentFailState.true], params[:value_method], params[:text_method])
end
#fields << render_sequence_nav(sequence_info, students_path)
fields << render(:partial => "resources_partials/sequence/nav", :locals => sequence_info.merge({:cancel_url => {:controller => :dashboard}}))
= render_form { fields }
Thanks for any response.
I think you are missing a comma between :student_fail_attribute and params[:StudentFailState.true].
You might want to think if params[:StudentFailState.true] is supposed to be there at all, unless it returns the collection you will most likely not get the expected results.

Resources