Im writing a simple statement which should check whether values in an array contain a 7.
I had the following in mind:
def checkforseven(an_array)
newArray = []
an_array.each do |num|
if num.include?(7)
newArray << num
end
end
newArray
end
array = [1,2,14,27]
exclaim(array)
But this not seem to work... Am getting a "nomethod error"
NoMethodError: undefined method `include?' for 1:Fixnum
Any thoughts on how I can solve this?
NoMethodError: undefined method `include?' for 1:Fixnum
As i said,the include should be used with an array.Currently you are iterating an_array and using include on its elements,which is wrong.
Try this
def checkforseven(an_array)
newArray = []
if an_array.include?(7)
newArray << an_array
end
newArray
end
Related
I have a helper method which returns array
def site
return Website::SITE.collect!{ |arr| arr if arr[1] != 'site_builder' }
end
Website::SITE return array in console
I call this method in view.
- site.each do |menu|
tr
td= menu[0]
Here it gives ActionView::Template::Error (undefined method `[]' for nil:NilClass):
Let's redefine the function like this:
def site
Website::SITE.compact.select{ |arr| arr if arr[1] != 'site_builder' }
end
It's because, the array Website::SITE contains nil value.
[["About ", "about"], ["Calendar", "calendar"], ["Gallery", "gallery"], ["Information", "information"], ["Manage ", "manage"], nil, ["Template", "website"]]
If you didn't put the method in the helpers folder but directly to the controller, then you have to add a line of code after your method to make it work.
def site
return Website::SITE.collect!{ |arr| arr if arr[1] != 'site_builder' }
end
helper_method :site
This should fix the error
Question I have a custom divide and conquer array sorter that I would like to use. This all works well until I try to use it on an array in my controller I get this message.. NoMethodError (undefined method '<=' for #<Entry:0x0000000ac7d850>): Any help would be greatly appreciated thank you!
here is my Entry model with the mergesort method I am calling in my controller.
def self.mergesort(container)
return container if (container.size <= 1)
mid = container.size / 2
left = container[0...mid]
right = container[mid...container.size]
merge(mergesort(left), mergesort(right))
end
def self.merge(left, right)
sorted = []
until left.empty? or right.empty?
(left.first <= right.first) ? sorted << left.shift : sorted << right.shift
end
sorted + left + right
end
Here is my Entry controller where I am trying to call it.
def pending_sort
#ent_sort = Entry.where("section = ? and approve_disapprove = ?", #mgr_section, '3')
#ent = Entry.mergesort(#ent_sort)
end
You probably have a nil for the first element of either left or right.
irb(main):001:0> left = []
=> []
irb(main):002:0> right = [1]
=> [1]
irb(main):003:0> left.first
=> nil
irb(main):004:0> left.first <= right.first
NoMethodError: undefined method `<=' for nil:NilClass
from (irb):4
from /usr/bin/irb:11:in `<main>'
You can fix the error by casting the nil to a different value. For example, if the values you are comparing are always integers you can change the following line:
(left.first <= right.first) ? sorted << left.shift : sorted << right.shift
to this:
(left.first.to_i <= right.first.to_i) ? sorted << left.shift : sorted << right.shift
But think about how it will affect your functionality... it may break something if it isn't what you actually want to do.
I'm bringing in xml data to my application controller, passing to an array and then passing the data stored in this array to the view and into a highchart. Can anyone help please, I've the vast majority of it done, I just can't see what I'm doing wrong.
def index
#doc = Nokogiri::XML(open("http://api.worldbank.org/countries/BRA/indicators/1.0.HCount.2.5usd?per_page=10&date=1960:2014"))
#values = Array.new(9)
for i in 0 .. 8
#values[i] = #doc.xpath('//wb:value')
end
end
I then call the data in my series:
data: [<%=#values[0]%>, <%=#values[1]%>, <%=#values[2]%>, <%=#values[3]%>, <%=#values[4]%>, <%=#values[5]%>, <%=#values[6]%>, <%=#values[7]%>, <%=#values[8]%>]
The error message is as below:
undefined method `[]' for nil:NilClass
highlighted area where the error is:
data: [<%=#values[0]%>, <%=#values[1]%>, <%=#values[2]%>, <%=#values[3]%>, <%=#values[4]%>, <%=#values[5]%>, <%=#values[6]%>, <%=#values[7]%>, <%=#values[8]%>] –
On line 6, you forgot to indicate #doc.xpath('//wb:value'), so it should be:
#values[i] = #doc.xpath('//wb:value')
doc is instance variable.
For the array issue, you could use:
#doc = Nokogiri::XML(open("http://api.worldbank.org/countries/BRA/indicators/1.0.HCount.2.5usd?per_page=10&date=1960:2014"))
m = #doc.xpath("//wb:value").collect(&:text)
#values = Array.new
m.each do |m|
#values << m
end
My search returns this hash bellow
{"product"=>[{:title=>"It's All About Shoes Barbie Shoe Tree 2010 Hallmark Ornament"}, {:title=>"Iron Lady Bug Key Holder - Hide-A-Key"}]}
here is the loop and the code that generates the hash
id = "B003TM2IDS,B004X75EX4"
ids = id.split(',')
response = []
prod = Hash.new
product = Hash.new
#fetch product title from amazon
for aid in ids do
res = Amazon::Ecs.item_lookup(aid, { :response_group => "ItemAttributes"})
res.items.each do |item|
prod[:title] = item.get("ItemAttributes/Title")
end
# hash
product = {"product" => response.push(prod.dup)}
end
#loop to print the titles - Not working
product.each do |item_prod|
puts item_prod.title
end
I do get the
undefined method `title' for # (NoMethodError)
My question are:
Is the Product hash correct?
Is the loop correct?
I've done this millions of times but some reason I can't see the problem with this
Thanks a lot in advance
Do as below:
product["product"].each do |prod|
puts prod[:title]
end
product["product"].each { |p| puts p[:title] }
I was using the following piece of code without any issues. the function querytags returns a set of "products". geturl function checks if a product has an image associated with it. All products with an image are pushed to productsProxy array
#query = params[:tag]
#products = queryTags(#query)
#productsProxy = Array.new
if #products != nil
#products.each do |p|
tempProduct = ProductProxy.new(p)
if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file'])
#productsProxy.push(tempProduct)
end
end
else
#productProxy = []
end
Then i tried to add another parameter in the URL and changed the querytags function accordingly.
#query = params[:tag]
#taxon = params[:taxon]
#products = queryTags(#query, #taxon)
#productsProxy = Array.new
if #products != nil
#products.each do |p|
tempProduct = ProductProxy.new(p)
if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file']) #now showing error
#productsProxy.push(tempProduct)
end
end
else
#productProxy = []
end
But I stated getting undefined method[]' for nil:NilClass` on the line:
if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file'])
I checked with the help of debugger that #products array is not empty. I am unable to figure out why suddenly i am getting this error. please can someone help
It's not about the "#products" array being empty or not - if it was empty, the "#products" iterator wouldn't do anything. The problem is that one of your products is either lacking an images attribute or the images[0] is not returning a hash. For debugging purposes I'd start by adding "break if p.images.nil?" to the top of your iterator and go from there.