ruby, unexpected kend and end errors - ruby

new to ruby, keep getting "kend and $end errors...Not too sure what i'm doing wrong.
Two options in this code, one should search for a user and return the tweet for each tweet which is a max of the given number. And other should search twitter tweets for a string and then return the result also.
require "rubygems"
require "twitter"
tweetsorlooks = String.new ARGV[1]
namesearchword = String.new ARGV[2]
number = String.new ARGV[3]
userurl = 'https://api.twitter.com/1/statuses/user_timeline.json?
include_entities=true&include_rts=true&screen_name=#{namesearchword }&count=#{number}'
searchurl = 'http://search.twitter.com/search.json?q=#
{namesearchword}&result_type=mixed'
statusresponse = RestClient.get(userurl)
userdata = statusresponse.body
userresult = JSON.parse(userdata)
queryresponse = RestClient.get(queryurl)
queryurl= queryresponse.body
queryresult= JSON.parse(queryurl)
if ARGV[1] == 'tweets'
puts
ref["userresult"].each do
puts tweet["from_user"] + " : " + tweet["text"]
end
else
puts
ref["queryresul"].each do
puts tweet["from_user"] + " : " + tweet["text"]
end

Get used to indent your code properly:
if ARGV[1] == 'tweets'
puts
ref["userresult"].each do
puts tweet["from_user"] + " : " + tweet["text"]
end
else
puts
ref["queryresul"].each do
puts tweet["from_user"] + " : " + tweet["text"]
end
now the problem is obvious.

An end is missing in the end. The outer if loop is not properly closed.

Related

else without rescue is useless and expecting keyword_end

This code gives me these errors in my ruby console:
1) warning: else without rescue is useless
2) syntax error, unexpected end-of-input, expecting keyword_end
Why am I getting both of these errors at the same time?
require 'nokogiri'
require 'httparty'
require 'byebug'
require 'awesome_print'
require 'watir'
def input #takes user input and grabs the url for that particular search
puts "1) Enter the job title that you want to search for \n"
j_input = gets.chomp
job = j_input.split(/ /).join("+")
puts "================================= \n"
puts "1/2)Do you want to input city-and-state(1) or zipcode(2)? \n"
choice = gets.chomp
if choice == "1"
puts "2) Enter the city that you want to search for \n"
city_input = gets.chomp
city = city_input.split(/ /).join("+")
puts "================================= \n"
puts "3) Enter the state that you want to search for \n"
state_input = gets.chomp
state = "+" + state_input
puts target_url = "https://www.indeed.com/resumes/?q=#{job}&l=#{city}%2C#{state}&cb=jt"
elsif choice == "2"
puts "Enter the zipcode that you want to search for \n"
zipcode = gets.chomp
puts target_url = "https://www.indeed.com/resumes?q=#{job}&l=#{zipcode}&cb=jt"
else
puts "error"
end
unparsed_page = HTTParty.get(target_url)
parsed_page = Nokogiri::HTML(unparsed_page)
resume_listing = parsed_page.css('div.sre-entry')
per_page = resume_listing.count
resumes = Array.new
counter = 0
result_count = parsed_page.css('div#result_count').text.split(' ')[0].to_f
page_count = (result_count.to_f / per_page.to_f ).ceil
current_count = 0
byebug
if counter <= 0
unparsed_page = HTTParty.get(target_url)
parsed_page = Nokogiri::HTML(unparsed_page)
resume_listing = parsed_page.css('div.sre-entry')
per_page = resume_listing.count
pagination_resume_listing.each do |resume_listing|
#resume_info = {
# title:
# link:
# skills:
# education:
#}
#resumes << resume_info
puts "Added #{resume_info[:title]}"
else
while current_count <= page_count * per_page
pagination_url = "https://www.indeed.com/resumes?q=#{job}&l=#{zipcode}&co=US&cb=jt&start=#{current_count}"
unparsed_pagination_page = HTTParty.get(pagination_url)
pagination_parsed_page = Nokogiri::HTML(unparsed_pagination_page)
pagination_resume_listing = pagination_parsed_page.css('div.sre-entry')
pagination_resume_listing.each do |resume_listing|
#resume_info = {
# title:
# link:
# skills:
# education:
#}
#resumes << resume_info
puts "Added #{resume_info[:title]}"
current_count += 50
end
end
end
end
end
It won't allow me to fix the else without rescue issue without telling me that it expects an extra end at the end of my code. Of course when I put the end there it does nothing and says that it wants another end
I would say that your code is horribly formatted, but it would first have to be formatted at all to be even that much. Once you format it, the answer is quite obvious, you have a mis-placed end.
puts "Added #{resume_info[:title]}"
# Should be and end here for the "do" block above
else
Here is what it should be:
require 'nokogiri'
require 'httparty'
require 'byebug'
require 'awesome_print'
require 'watir'
def input #takes user input and grabs the url for that particular search
puts "1) Enter the job title that you want to search for \n"
j_input = gets.chomp
job = j_input.split(/ /).join("+")
puts "================================= \n"
puts "1/2)Do you want to input city-and-state(1) or zipcode(2)? \n"
choice = gets.chomp
if choice == "1"
puts "2) Enter the city that you want to search for \n"
city_input = gets.chomp
city = city_input.split(/ /).join("+")
puts "================================= \n"
puts "3) Enter the state that you want to search for \n"
state_input = gets.chomp
state = "+" + state_input
puts target_url = "https://www.indeed.com/resumes/?q=#{job}&l=#{city}%2C#{state}&cb=jt"
elsif choice == "2"
puts "Enter the zipcode that you want to search for \n"
zipcode = gets.chomp
puts target_url = "https://www.indeed.com/resumes?q=#{job}&l=#{zipcode}&cb=jt"
else
puts "error"
end
unparsed_page = HTTParty.get(target_url)
parsed_page = Nokogiri::HTML(unparsed_page)
resume_listing = parsed_page.css('div.sre-entry')
per_page = resume_listing.count
resumes = Array.new
counter = 0
result_count = parsed_page.css('div#result_count').text.split(' ')[0].to_f
page_count = (result_count.to_f / per_page.to_f ).ceil
current_count = 0
byebug
if counter <= 0
unparsed_page = HTTParty.get(target_url)
parsed_page = Nokogiri::HTML(unparsed_page)
resume_listing = parsed_page.css('div.sre-entry')
per_page = resume_listing.count
pagination_resume_listing.each do |resume_listing|
#resume_info = {
# title:
# link:
# skills:
# education:
#}
#resumes << resume_info
puts "Added #{resume_info[:title]}"
end
else
while current_count <= page_count * per_page
pagination_url = "https://www.indeed.com/resumes?q=#{job}&l=#{zipcode}&co=US&cb=jt&start=#{current_count}"
unparsed_pagination_page = HTTParty.get(pagination_url)
pagination_parsed_page = Nokogiri::HTML(unparsed_pagination_page)
pagination_resume_listing = pagination_parsed_page.css('div.sre-entry')
pagination_resume_listing.each do |resume_listing|
#resume_info = {
# title:
# link:
# skills:
# education:
#}
#resumes << resume_info
puts "Added #{resume_info[:title]}"
current_count += 50
end
end
end
end
Lesson here is to ALWAYS format your code, for everyone's sake, most of all your own. There is no excuse to not be formatted, and not doing so leads to trivial problems like this that are difficult to find.
NOTE
I did not test this or run it, simply formatted, which made the mis-matched end obvious.

Ruby undefined method `+' for nil:NilClass

I'm a total beginner in ruby but I can't get out of this issue
I get these when I run the code, it all works well until the end:
INPUT TEXT: It all works well until
INPUT SUBTEXT: ll
TEXT: It all works well until SUBTEXT: ll
OUTPUT:
4
15
undefined method +' for nil:NilClass
(repl):18:ininitialize'
puts "\nINPUT TEXT:"
#text = gets.chomp
puts "\nINPUT SUBTEXT:"
#subtext = gets.chomp
puts "\nTEXT: " + #text
puts "SUBTEXT: " + #subtext
puts "\n"
i = #text.index (#subtext)
puts "OUTPUT:"
while i != -1
puts i.to_s + ' '
i = #text.index #subtext, i+1
end
In Ruby, String#index doesn't return -1 when the substring is not found; it returns nil. Change your condition from while i != -1 to while i. (This works because, unlike some other languages, Ruby considers the value 0 to be true; only false and nil are false.)
Index return nil if substrings doesn't exist. So this should solve this issue
#text = gets.chomp
puts "\nINPUT SUBTEXT:"
#subtext = gets.chomp
puts "\nTEXT: " + #text
puts "SUBTEXT: " + #subtext
puts "\n"
i = #text.index (#subtext)
puts "OUTPUT:"
while i
puts i.to_s + ' '
i = #text.index #subtext, i+1
end

Ruby error: in `block in process': undefined method `^' for "4":String (NoMethodError)

Trying to run an rc4 algorithm and it's not recognizing the XOR method? Or is something else going on? I get the error when it gets to def process(text).
Error:
rc4.rb:26:in block in process': undefined method^' for "4":String (NoMethodError)
from rc4.rb:26:in upto'
from rc4.rb:26:inprocess'
from rc4.rb:21:in encrypt'
from rc4.rb:48:in'
Code:
class Rc4
def initialize(str)
#q1, #q2 = 0, 0
#key = []
str.each_byte {|elem| #key << elem} while #key.size < 256
#key.slice!(256..#key.size-1) if #key.size >= 256
#s = (0..255).to_a
j = 0
0.upto(255) do |i|
j = (j + #s[i] + #key[i] )%256
#s[i], #s[j] = #s[j], #s[i]
end
end
def encrypt!(text)
process text
end
def encrypt(text)
process text.dup
end
private
def process(text)
0.upto(text.length-1) {|i| text[i] = text[i] ^ round}
text
end
def round
#q1 = (#q1 + 1)%256
#q2 = (#q2 + #s[#q1])%256
#s[#q1], #s[#q2] = #s[#q2], #s[#q1]
#s[(#s[#q1]+#s[#q2])%256]
end
end
puts "Enter key."
keyInput = gets.chomp
keyInput = keyInput.to_s
encryptInstance = Rc4.new(keyInput)
decryptInstance = Rc4.new(keyInput)
puts "Enter plaintext."
plainInput = gets.chomp
plainInput = plainInput.to_s
cipherText = encryptInstance.encrypt(plainInput)
puts "Plaintext is: " + plainInput
puts "Ciphertext is: " + cipherText
decryptedText = decryptInstance.encrypt(cipherText)
puts "Decrypted text is: " + decryptedText
text[i] is a string here. Use text[i].to_i
This should work
0.upto(text.length-1) {|i| text[i] = (text[i].ord ^ round).chr}
Since you're doing encryption, converting "4" to 4 would be a big mistake. We operate on the encodings and convert it back.

Why can't I convert a fixnum into a string?

I am creating a quiz-maker program in Ruby. It opens and reads a text file, and is able to make a quiz of of the questions and answers in the text file. I am trying to let the user know how many question they got wrong after they complete the quiz.
The error I am getting is:
quiz.rb:180:in `+': can't convert Fixnum into String (TypeError)
from quiz.rb:180:in `<main>'
I get this error after it goes through all the questions.
Here is my code. correct_count is where I try to subtract 1 from the starting 10 everytime someone gets a question wrong. Let me know if you would like to see the text file.
questions = File.open("question.txt","r+")
array = {}
contents = questions.readlines
questions.close
contents.collect! do |x|
x.chomp
end
contents.collect! do |x|
x.split(',')
end
contents.each do |x|
array[x[0]] = x
end
correct_count = 10
question1 = contents[0][1]
choice11 = contents[0][2]
choice12 = contents[0][3]
answer11 = contents[0][4]
question2 = contents[1][1]
choice21 = contents[1][2]
choice22 = contents[1][3]
answer21 = contents[1][4]
question3 = contents[2][1]
choice31 = contents[2][2]
choice32 = contents[2][3]
answer31 = contents[2][4]
question4 = contents[3][1]
choice41 = contents[3][2]
choice42 = contents[3][3]
answer41 = contents[3][4]
question5 = contents[4][1]
choice51 = contents[4][2]
choice52 = contents[4][3]
answer51 = contents[4][4]
question6 = contents[5][1]
choice61 = contents[5][2]
choice62 = contents[5][3]
answer61 = contents[5][4]
question7 = contents[6][1]
choice71 = contents[6][2]
choice72 = contents[6][3]
answer71 = contents[6][4]
question8 = contents[7][1]
choice81 = contents[7][2]
choice82 = contents[7][3]
answer81 = contents[7][4]
question9 = contents[8][1]
choice91 = contents[8][2]
choice92 = contents[8][3]
answer91 = contents[8][4]
question10 = contents[9][1]
choice101 = contents[9][2]
choice102 = contents[9][3]
answer101 = contents[9][4]
topic = contents[11][1]
puts "Welcome to this " + topic + " quiz. Please spell the answers exactly right to get them correct (don't worry about caps). Good Luck!"
puts question1
puts choice11 + " or " + choice12 + "?"
user1 = gets.chomp
if user1.downcase == answer11.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question2
puts choice21.downcase + " or " + choice22 + "?"
user2 = gets.chomp
if user2.downcase == answer21.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question3
puts choice31.downcase + " or " + choice32.downcase + "?"
user3 = gets.chomp
if user3.downcase == answer31.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question4
puts choice41.downcase + " or " + choice42.downcase + "?"
user4 = gets.chomp
if user4.downcase == answer41.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question5
puts choice51.downcase + " or " + choice52.downcase + "?"
user5 = gets.chomp
if user5.downcase == answer51.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question6
puts choice61.downcase + " or " + choice62.downcase + "?"
user6 = gets.chomp
if user6.downcase == answer61.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question7
puts choice71.downcase + " or " + choice72.downcase + "?"
user7 = gets.chomp
if user7.downcase == answer71.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question8
puts choice81.downcase + " or " + choice82.downcase + "?"
user8 = gets.chomp
if user8.downcase == answer81.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
if user9.downcase == answer91.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "Next question: " + question10
puts choice101.downcase + " or " + choice102.downcase + "?"
user10 = gets.chomp
if user10.downcase == answer101.downcase
puts "correct"
else
puts "incorrect" and correct_count -1
end
puts "you got" + correct_count + "out of 10 correct"
Change:
puts "you got" + correct_count + "out of 10 correct"
to:
puts "you got" + correct_count.to_s + "out of 10 correct"
or:
puts "you got #{correct_count} out of 10 correct"
NOTE:
correct_count = 10
puts "incorrect" and correct_count -1
correct_count # => 10
# >> incorrect
correct_count still evaluates to 10.
You should be doing:
if user6.downcase == answer61.downcase
puts "correct"
else
puts "incorrect"
correct_count -= 1
end

How to generate xml_builder ruby code from an XML file

I've got an xml file. How could I generate xml_builder ruby code out of that file?
Notice - I'm sort of going backwards here (instead of generating xml, I'm generating ruby code).
Pretty formatting isn't a big deal - I can always run it through a formatter later.
It's sort of impossible, not unlike if you asked "how to generate Ruby script that outputs number 3", for the answer could be:
puts 3
or
puts 2+1
or
puts [1,2,3].count
etc.
So, one answer to your question would be:
xml = File.read('your.xml')
puts "puts <<EOF\n#{xml}\nEOF"
Anyway, if you would just want to generate Builder based script which just generates your XML node-for-node, I guess it would be easiest using XSLT. That's a language constructed exactly for such purposes - transforming XMLs.
Here's what I eventually came up with:
#!/usr/bin/env ruby
require "rexml/document"
filename = ARGV[0]
if filename
f = File.read(filename)
else
raise "Couldn't read file: `#{filename}'"
end
doc = REXML::Document.new(f)
def self.output_hash(attributes={})
count = attributes.size
str = ""
index = 0
attributes.each do |key, value|
if index == 0
str << " "
end
str << "#{key.inspect} => "
str << "#{value.inspect}"
if index + 1 < count
str << ", "
end
index += 1
end
str
end
def self.make_xml_builder(doc, str = "")
doc.each do |element|
if element.respond_to?(:name)
str << "xml.#{element.name}"
str << "#{output_hash(element.attributes)}"
if element.length > 0
str << " do \n"
make_xml_builder(element, str)
str << "end\n"
else
str << "\n"
end
elsif element.class == REXML::Text
string = element.to_s
string.gsub!("\n", "")
string.gsub!("\t", "")
if !string.empty?
str << "xml.text!(#{string.inspect})\n"
end
end
end
str
end
puts make_xml_builder(doc)
After generating that, I then formatted it in Emacs.

Resources