1

I am new to ruby and rails, so I am still attempting to get a handle on the syntax and structure of ruby. I am following a tutorial to import a csv file using a task and rake. I keep getting a syntax error though. I am not sure what I am missing, I do not see any difference between the example and my code.

require 'csv'

    desc "Import Voters from CSV File"

    task :import => [:environment] do

      file ="db/my.csv"

      CSV.foreach(file, :headers => true) do |row|
        Voter.create{
          :last_name => row[0]
        }  

      end






(See full trace by running task with --trace)
Erics-MacBook-Air:cloudvoters ecumbee$ rake db:import --trace
rake aborted!
/Users/ecumbee/Desktop/cloudvoters/lib/tasks/import.rake:11: syntax error, unexpected tASSOC, expecting '}'
      :last_name => row[0], 
                   ^
/Users/ecumbee/Desktop/cloudvoters/lib/tasks/import.rake:12: syntax error, unexpected '}', expecting '='
    }  
     ^

2 Answers 2

2

You're missing the parenthesis which would surround the hash you're giving as a parameter of the create function

    Voter.create({
      :last_name => row[0]
    })

You can also skip both parenthesis & curly brackets

    Voter.create :last_name => row[0]
Sign up to request clarification or add additional context in comments.

4 Comments

the tutorial had neither of those. is it a change of syntax or a mistake by the original author? also i am now getting an error on the end statement syntax error, unexpected $end, expecting kEND end
@Eric: There is ambiguity with Voter.create{...}. Is it a Hash argument or a block? How ambiguity is resolved can vary between Ruby versions so your tutorial is probably just old. I put parentheses on my method calls because I'm tired of this sort of nonsense; most Ruby people will disagree with me on this but I'm a professional heretic so I don't mind.
@muistooshort i assume its a hash argument. if i understand properly it should be a call to create a new object based on my voter model.
im still stumped on where the unexpected end is coming from
1

As @pjam pointed out, you have to use parenthesis before curly braces, or skip both.

For eg.Voter.create :last_name => row[0]

The other problem related to unexpected $end, expecting kEND end is you have a missing end

require 'csv'

desc "Import Voters from CSV File"

task :import => [:environment] do

  file ="db/my.csv"

  CSV.foreach(file, :headers => true) do |row|
    Voter.create{
      :last_name => row[0]
    }  

  end

You are ending CSV.foreach block with the end on last line but not ending the task So by adding extra end this error will be removed.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.