简体   繁体   中英

Split Function showing error in Ruby 1.8.7

I have a piece of code I have written in Ruby 1.8.7 Variable emotes has a list of emoticons separated by a space. However, when I apply the split function, I get an error

lines=[]
keywords=""
emotes=""
Dir["/home/pnpninja/Downloads/aclImdb/train/formatted neg/*"].each do |reviewfile|
  sum_emote = 0
  sum_keyword = 0
  lines = File.foreach(reviewfile.to_s).first(2)
  lines[0].gsub!("\n",'')
  keywords = lines[0].split(" ")
  emotes = lines[1].split(" ")
  keywords.each { |keyword| sum_keyword = sum_keyword + keywordhash[keyword] }
  emotes.each { |emote| sum_emote = sum_emote + emotehash[emote] }
  senti=""
  if sum_emote+sum_keyword >= 0
    senti = "Positive"
  else
    senti = "Negative"
  end
  vv = reviewfile.gsub('formatted neg','analysed neg')
  fin = File.open(vv.to_s, 'a')
  fin << "Emote Weight = #{sum_emote}\n"
  fin << "Keyword Weight = #{sum_keyword}\n"
  fin << "Sentiment : #{senti}"
  fin.close
end

The error I get is

NoMethodError: private method `split' called for nil:NilClass

at line

emotes = lines[1].split(" ")

THe second line in each file could be empty or not.

The error is telling you that you can't call split on a nil object.

Rewrite your code to ensure there are no nil objects or ensure nothing is done if the object in question is nil

unless lines[1].nil?
 emotes = lines[1].split(" ")
 emotes.each { |emote| sum_emote = sum_emote + emotehash[emote] }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM