I ran this piece of code earlier:
require "awesome_print"
require "rexml/document"
require "debugger"
include REXML
class Scrapper
attr_reader :data
def initialize
file = File.new("./cia-1996.xml")
#data = REXML::Document.new(file)
end
def get_country_inflation
inflation_hash = {}
XPath.match( data, "//country").map { |element|
inflation_hash[element.attributes["name"]] = element.attributes["inflation"].to_i}
nested_array = inflation_hash.to_a
sorted_array = nested_array.sort_by {|country, inflation_value| inflation_value}.reverse
puts "The countries with the highest inflation indexes in 1996 were:"
first_five = sorted_array.first(5)
first_five.each do |item|
puts "#{item[0]}, with an inflation index of #{item[1]}"
end
end
end
end
sample = Scrapper.new
sample.get_country_inflation
After making some edits, I now get error message
economics_challenge.rb:36: syntax error, unexpected keyword_end, expecting end-of-input
Can you please give me pointers as to where the mistake/typo might be (been starring at it for a while now and would appreciate feedback from a new set of eyes).
Thank you so much!
Edit:
so I made the changes suggested but I got more error messages:
economics_challenge.rb:26: syntax error, unexpected tSTRING_DEND, expecting keyword_end
economics_challenge.rb:29: syntax error, unexpected tSTRING_DEND, expecting '}'
...flation_value| inflation_value}.reverse
... ^
economics_challenge.rb:35: syntax error, unexpected keyword_end, expecting '}'
economics_challenge.rb:46: syntax error, unexpected end-of-input, expecting '}'
line 26 refers to the 2nd line in the piece of code below: piece of code (and I think this is where the original problem is):
XPath.match( data, "//country").map do |element|
inflation_hash[element.attributes["name"]] = element.attributes["inflation"].to_i}
end
line 29 is:
sorted_array = nested_array.sort_by {|country, inflation_value| inflation_value}.reverse
I will attempt to fix the error in 29 by calling reverse on sorted array and saving that to a variable.
Line 35 is an end statement and there is no line 46.
Any tips?
Thank you!
2nd Edit:
Wow! I cannot believe I failed to realize that I didn't end many things. I will be sticking to the do andend syntax from now on.
Thank you both for helping me out so much … really appreciate it!
The problem is you have one extra end
As #david-grayson states, had your indentations been correct, you may have spotted it.
This of course, is given the code as you presented it here. It may not be exactly that, though the error message matches the found issue.
Here is the code with indentation, some style changes, and no syntax errors:
require 'awesome_print'
require 'rexml/document'
require 'debugger'
include REXML
class Scrapper
attr_reader :data
def initialize
file = File.new('./cia-1996.xml')
#data = REXML::Document.new(file)
end
def get_country_inflation
inflation_hash = {}
XPath.match(data, '//country').map do |element|
inflation_hash[element.attributes['name']] = element.attributes['inflation'].to_i
end
nested_array = inflation_hash.to_a
sorted_array = nested_array.sort_by do |country, inflation_value|
inflation_value
end.reverse
puts 'The countries with the highest inflation indexes in 1996 were:'
first_five = sorted_array.first(5)
first_five.each do |item|
puts "#{item[0]}, with an inflation index of #{item[1]}"
end
end
end
sample = Scrapper.new
sample.get_country_inflation
Your indentation is messed up starting here:
XPath.match( data, "//country").map { |element|
inflation_hash[element.attributes["name"]] = element.attributes["inflation"].to_i}
nested_array = inflation_hash.to_a
The last line of that excerpt should be unindented by one level because the block you passed to "map" was terminated on the second line by the right bracket.
Try fixing that and everything after it.
Also, here is a tip: always write multi-line blocks using do and end and put the end on its own line. Then you could would be:
XPath.match( data, "//country").map do |element|
inflation_hash[element.attributes["name"]] = element.attributes["inflation"].to_i
end
nested_array = inflation_hash.to_a
Related
Very new to Ruby, unable to see the titular syntax error in this bit of code:
#! /usr/bin/env ruby
require 'sensu-plugin/metric/cli'
class MetricAvailableUpdates < Sensu::Plugin::Metric::CLI::Graphite
option :scheme,
description: 'Metric naming scheme',
long: '--scheme SCHEME',
short: '-s SCHEME',
default: "#{Socket.gethostname}"
def run
# Get the metrics.
output = %x[/usr/lib/update-notifier/apt-check --human-readable]
output_lines = output.split(/(\n)/)
metrics = {}
updates_pattern = " packages can be updated."
updates = output_lines[0].tr(upgrades_pattern, "").to_i
metrics[:available_updates] = updates
security_updates_pattern = " updates are security updates."
security_updates = output_lines[2].tr(security_updates_pattern, "").to_i
metrics[:available_security_updates] = security_updates
# Print them in graphite format.
metrics.each do |k, v|
output [config[:scheme], k].join('.'), v
end
# Done
ok
end
end
I can add the code that precedes this if the syntax error is in fact before this section. Edit: added complete file contents per comment request
The complete error, in case that is useful:
./metrics-available-updates.rb:29: syntax error, unexpected ',', expecting keyword_end
output [config[:scheme], k].join('.'), v
If you play around a bit, you will notice that the syntax error goes away either when you comment out the offending line, or alternatively the line
output = %x[/usr/lib/update-notifier/apt-check --human-readable]
When Ruby parses a file, it needs to guess, whether a symbol denotes a method call, or a variable reference. In this case, output springs into existence as a variable, but further down, you write
output [config[:scheme], k].join('.'), v
which means it suddenly becomes a method call.
I admit that the Ruby lexer should give a more helpful error message....
Add the parentheses
...
metrics.each do |k, v|
output([config[:scheme], k].join('.'), v)
end
...
Figured this out on my own -- code at the bottom (needed to raise an exception because a couple of the strings I had were invalid).
I've been having an issue in that I keep getting a 400 error when I run the following code. I've spot checked individual values and they all seem to work, and I can get this to run fine with just one value in my posts array (which has about 350 values right now). Any help would be greatly appreciated!
require 'open-uri'
require 'JSON'
posts = [blahblah1, blahblah2... blahblah350]
api_key = "REALLYLONGSTRING"
output = File.open("facebook-posts.csv", "w+")
posts.each do |post|
obj = JSON.parse(open("https://graph.facebook.com/v2.3/#{post.to_s}?access_token=#{api_key}").read)
output << obj
output << "\n"
end
output.close
Working code:
posts.each do |post|
begin
obj = JSON.parse(open("https://graph.facebook.com/v2.3/#{post.to_s}?access_token=#{api_key}").read)
rescue OpenURI::HTTPError
next
end
output << obj
output << "\n"
While running the RSPEC test as shown below im getting this error:
Using Accessor#strict_set for specs
SyntaxError: /home/sam/projects/logstash.king-foo.dev/ansible/roles/logstash/spec/syslog.rb:6: syntax error, unexpected kEND
end
^
load at org/jruby/RubyKernel.java:1101
(root) at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:1
each at org/jruby/RubyArray.java:1613
load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
run at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/command_line.rb:22
I tried messing around with the syntax but without success.
files = Dir['../configs/filter*.conf']
##configuration = String.new
files.sort.each.do |file|
##configuration << File.read(file)
end
describe "my first logstash rspec test", :if => RUBY_ENGINE == "jruby" do
extend LogStash::RSpec
config(##configuration)
... some code here ...
end
Does anybody know what i'm doing wrong?
Why do i get a syntax error for the end statement ander the ##configuration variable?
The error means there was an unexpected end in your code. Just simply replace the 3rd line with
files.sort.each do |file|
I optionally recommend you use { and } instead of do and end. The { and } are space-insensitive and you are less likely to receive an error than do and end.
hate to ask this, but i can't for he life of me find this end error, can anyone help> please, thanks.
require_relative 'playlist'
describe playlist do
before do
#playlist = Playlist.new("kermit")
end
context "being played with one movie" do
before do
#initial_rank= 10
#Movie = Movie.new("goonies", #initial_rank)
#playlist.add_movie(#movie)
end
it "give the movie a thumbs up if high number is rolled" do
#playlist.play(5)
#movie.rank.should == #initial_rank + 1
end
it "skips the movie if a medium niumber is rolled" do
#playlist.play(3)
#movie.rank.should == #initial_rank
end
end
end
I have the following code, which gives me an invalid byte sequence error pointing to the scan method in initialize. Any ideas on how to fix this? For what it's worth, the error does not occur when the (.*) between the h1 tag and the closing > is not there.
#!/usr/bin/env ruby
class NewsParser
def initialize
Dir.glob("./**/index.htm") do |file|
#file = IO.read file
parsed = #file.scan(/<h1(.*)>(.*?)<\/h1>(.*)<!-- InstanceEndEditable -->/im)
self.write(parsed)
end
end
def write output
#contents = output
open('output.txt', 'a') do |f|
f << #contents[0][0]+"\n\n"+#contents[0][1]+"\n\n\n\n"
end
end
end
p = NewsParser.new
Edit: Here is the error message:
news_parser.rb:10:in 'scan': invalid byte sequence in UTF-8 (ArgumentError)
SOLVED: The combination of using:
#file = IO.read(file).force_encoding("ISO-8859-1").encode("utf-8", replace: nil)
and
encoding: UTF-8
solve the issue.
Thanks!
The combination of using: #file = IO.read(file).force_encoding("ISO-8859-1").encode("utf-8", replace: nil) and #encoding: UTF-8 solved the issue.
While this question already has an accepted answer, I found it while having the same problem with a different style of opening the file:
File.open(file_name).each_with_index do |line, index|
line.gsub!(/[{}]/, "'")
puts "#{index} #{line}"
end
I found that my input file was encoded in ISO-8859-1, so I changed it to the following to avoid the error:
File.open(file_name, 'r:ISO-8859-1:utf-8').each_with_index do |line, index|
line.gsub!(/[{}]/, "'")
puts "#{index} #{line}"
end
See the documentation for the optional mode argument of the File.open method for more details.