Abhradip
Abhradip

Reputation: 413

Issues related to method split

I am developing a rails app. I want to split the sentence typed in a searchbox in my app using split(" "). But I am getting undefined method `split' for nil:NilClass error. I am using form data and since the form search box data is empty during page loading,I am getting this error.

My code is:-

def string_array_conversion(sentence)
 sen_array=Array.new
 values = sentence.split()

 values.each do |value|
  sen_array.push(value)
  puts value
 end
 puts "this is the array"
 puts sen_array
 return sen_array
end

Here the function parameter 'sentence' is a form data. It is in the caller method :params[pt]

The code that is calling the method is:

def new

@emp=Employee.new
@emps=Employee.all

@aut=Autocomp.new
@auts=Autocomp.all

@check=params[:pt]
puts @check

ret_sen_array=string_array_conversion(@check)
puts ret_sen_array
end

Please tell me how to solve this issue.

Upvotes: 0

Views: 141

Answers (4)

Rajnik
Rajnik

Reputation: 83

values = sentence.split()

Replace above line to following line.

values = if sentence.present?
  sentence.split()
else
  []
end

Upvotes: 1

Daniel Ruiz
Daniel Ruiz

Reputation: 620

I would take another approach to solve this problem.

In Ruby, nil responds to the method .to_s and returns an empty string (""). In addition, a string can respond to this method and returns the same string (it's an idempotent operation). So, I'll call the method .to_s of the sentence variable to ensure working with strings:

    def string_array_conversion(sentence)
     sen_array=Array.new
     values = sentence.to_s.split()

     values.each do |value|
      sen_array.push(value)
      puts value
     end
     puts "this is the array"
     puts sen_array
     return sen_array
    end

Upvotes: 0

M. Karim
M. Karim

Reputation: 942

The cause of the error is value of sentence is nil. Make sure the value of sentence is not nil. You can control the exception like this,

def string_array_conversion(sentence)
 return unless sentence

 sen_array=Array.new
 values = sentence.split()

 values.each do |value|
  sen_array.push(value)
  puts value
 end
 puts "this is the array"
 puts sen_array
 return sen_array
end

Upvotes: 0

Ursus
Ursus

Reputation: 30056

sentence arrives nil into your method. We need the code that calls string_array_conversion

Upvotes: 0

Related Questions