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.
values = sentence.split()
Replace above line to following line.
values = if sentence.present?
sentence.split()
else
[]
end
sentence arrives nil into your method. We need the code that calls string_array_conversion
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
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
Related
I have been getting this error, no implicit conversion of Symbol into Integer. I searched for this error but don't really understand it. Code is at the bottom. Once it gets to this "if q[:text_field].is? Array" that is when it gives the error and I'm sure that the rest of that code is wrong. But no idea how to fix it.
pages = Vovici::API.new(#pid).survey_structure
This is a sample of the api data that I'm calling with the code above.
[{:q_fill_in=>
{:heading=>{:text=>"1"},
:instructions=>{:text=>nil},
:body=>{:text=>"Pac"},
:list_caption=>{:text=>{:#type=>"plain"}},
:total_label=>{:text=>"Total"},
:text_field=>
[{:label=>{:text=>"first"},
:preselection=>{:text=>{:#type=>"plain"}},
:symbol=>{:text=>{:#type=>"plain"}},
:#id=>"1",
:#dbheading=>"Q1_1",
:#row=>"0",
:#size=>"20",
:#xmltype=>"text",
:#required=>"false",
:#compare_expression=>"-1",
:#topic_first=>"true",
:#slider=>"false",
:#sliderstep=>"1",
:#published=>"true",
:#usecalendarpopup=>"true",
:#insert_symbol_left=>"false",
:#label_width=>"3",
:#text_area_width=>"9"},
{:label=>{:text=>"id"},
:preselection=>{:text=>{:#type=>"plain"}},
:symbol=>{:text=>{:#type=>"plain"}},
:#id=>"2",
:#dbheading=>"Q1_2",
:#row=>"0",
:#size=>"20",
:#xmltype=>"text",
:#required=>"false",
:#compare_expression=>"-1",
:#topic_first=>"true",
:#slider=>"false",
:#sliderstep=>"1",
:#published=>"true",
:#usecalendarpopup=>"true",
:#insert_symbol_left=>"false",
:#label_width=>"3",
:#text_area_width=>"9"}],
:#dbheading=>"Q1"}
This is code from my rb file
def process
pages = Vovici::API.new(#pid).survey_structure
pages.each do |page|
if page[:q_fill_in]
process_fill_in(*page[:q_fill_in])
end
end
end
def process_fill_in(*questions)
questions.each do |q|
if q[:text_field].is? Array
sub_qs = q[:text_field]
else
sub_qs = [q[:text_field]]
end
q_text = clean_question_text(q[:body][:text])
sub_qs.each do |sq|
sub_text = clean_question_text(sq[:label][:text])
q_name = [q_text, sub_text.reject { |i| i.nil? || i.empty? }.join("--")]
#survey.questions.create!(qheader: sq[:#dbheading], qtext: q_name)
end
end
end
def clean_question_text(text)
match = /( )?(<.*?>)?(.+)( )?(<\/.*>)?/.match(text)
match[3]
end
Can anyone please help?
This error means that you've used [] on an array but you've passed something that doesn't make sense to an array. In this particular case it's telling you that q which you are trying to use as a hash is in fact an array.
This is happening because process_fill_in(*page[:q_fill_in]) is turning the hash into an array of key-value pairs (because of the *). I'm not sure why you've got a splat there at all.
Hi i had created a small ruby project which consists of JSON file. I stored the JSON data into hash keys. AND worte a method to access the data which is present in hash key using user input. But when i try to send use the user input i am getting this error
how_many_ingredients': undefined methodkeys' for nil:NilClass (NoMethodError)
I found this link with same question and tried that solution but still i'm getting the same error
Accessing Hash Keys with user inputted variables, NoMethodError
File one where all the methods are written
require 'json'
class Methods
attr_accessor :name, :text
def initilize(name)
#name = name
#text = text
end
def how_many_ingredients(text)
puts 'text'
file = File.read('a.json')
hash = JSON.parse(file)
#puts hash['recipes']['pizza'].keys
puts hash['recipes'][text].keys
end
end
File 2 where how_Many_ingredients method is accessed, I can see that the variable is passed to that method
require './1'
class Hello < Methods
person = Methods.new
person.test
puts "enter recipie"
person.name
str = gets
person.how_many_ingredients str
end
Note that when you use gets, the input can contain newline and carriage return characters. You'll need to use gets.chomp to filter these. This is likely the cause of the issue in your program.
Compare the following two:
> puts gets.size
"Hello!"
# 7
> puts gets.chomp.size
"Hello!"
# 6
Note that you'll still need to extend your program to account for user inputted keys that are not in your hash.
Your code assumes that there will always be a hash stored at hash['recipes'][text] - you need to cater to the cases where it isn't.
A simple way to do this is to work your way down through the hash with && symbols - if any step is nil (or false), the line will return nil (or false) rather than exploding. eg
puts hash['recipes'] && hash['recipes'][text].is_a?(Hash) && hash['recipes'][text].keys
Note i'm testing that hash['recipes'][text] is a hash (rather than just a string for example) before calling .keys on it.
I'm probably missing something really obvious here. I have the following Ruby method:
def pair_array
return self.pair.each_slice(2) {
|x| puts x.join(" & ")
}.to_s
end
When I try to display the value of this method in my Rails view by calling #team.pair_array nothing appears, but the correct value gets printed on the console. I know this is probably because I'm using puts. How can I get the result of this method to display in my view?
You're confusing printing with returning a value. puts returns nil, and each_slice does not return the result of the block anyway. What you want is this:
def pair_array
pair.each_slice(2).map {|arr| arr.join ' & '}
end
Initially I import data in datatype Hash, in that i have a column called schedule, I need type of the particular column "schedule" from my db.
my tried code is
schedule = scheduleWorld.all
schedule.each do |sec|
sec.attributes.each do |key, value, type|
puts "%%%%%%%%%%%%%%%%%%%%%%%%%"
puts key
puts value
puts type
puts "%%%%%%%%%%%%%%%%%%%%%%%%%"
end
end
By this am getting nil in type, i tried another code is
schedule = scheduleWorld.where({schedule:{$type=>2}})
error is
undefined method `specify' for nil:NilClass
(eval):2:in `where'
anyone have idea about this?
Type is just one key-value pair in a mongodb document's attributes hash.
So you can always fetch it like this. I'm using Mongoid.
The exact name may vary on you ORM.
schedule = scheduleWorld.all
schedule.each do |sec|
type = sec.attributes["_type"]
sec.attributes.each do |key, value|
puts "%%%%%%%%%%%%%%%%%%%%%%%%%"
puts key
puts value
puts "%%%%%%%%%%%%%%%%%%%%%%%%%"
end
end
I m in a situation where i need to convert an Object to string so that i can check for Invalid characters/HTML in any filed of that object.
Here is my function for spam check
def seems_spam?(str)
flag = str.match(/<.*>/m) || str.match(/http/) || str.match(/href=/)
Rails.logger.info "** was spam #{flag}"
flag
end
This method use a string and look for wrong data but i don't know how to convert an object to string and pass to this method. I tried this
#request = Request
spam = seems_spam?(#request.to_s)
Please guide
Thanks
You could try #request.inspect
That will show fields that are publicly accessible
Edit: So are you trying to validate each field on the object?
If so, you could get a hash of field and value pairs and pass each one to your method.
#request.instance_values.each do |field, val|
if seems_spam? val
# handle spam
end
If you're asking about implementing a to_s method, Eugene has answered it.
You need to create "to_s" method inside your Object class, where you will cycle through all fields of the object and collecting them into one string.
It will look something like this:
def to_s
attributes.each_with_object("") do |attribute, result|
result << "#{attribute[1].to_s} "
end
end
attribute variable is an array with name of the field and value of the field - [id, 1]
Calling #object.to_s will result with a string like "100 555-2342 machete " which you can check for spam.