no implicit conversion of nil into String error
One of (or more) values in string
finalStatsFile.puts col_date+", "+col_constant1+", "+ col_appYear+", "+col_statsDesc+", "+col_constant2+", "+col_keyStats+", "+col_weeklyTotal
became nil
. To fix the output you should explicitly cast them to strings:
finalStatsFile.puts col_date.to_s + ", " +
col_constant1.to_s + ", " +
col_appYear.to_s + ", " +
col_statsDesc.to_s + ", " +
col_constant2.to_s + ", " +
col_keyStats.to_s + ", " +
col_weeklyTotal.to_s
BTW, the whole clause might be rewritten in more rubyish manner:
finalStatsFile.puts [ col_date,
col_constant1,
col_appYear,
col_statsDesc,
col_constant2,
col_keyStats,
col_weeklyTotal ].map(&:to_s).join(', ')
Ruby: undefined method `[]' for nil:NilClass when trying to get Enumerator on an Array of Hashes
undefined method `[]' for nil:NilClass
says you tried to do something[index]
but something
is nil
. Ruby won't let you use nil
as an array (ie. call the []
method on it).
The problem is not on the attributs.each
line but on the line following which calls the []
method on attribut
.
typeAttribut = attribut['objectTypeAttribute']
This indicates something in attributs
is nil. This could happen if attributsParam
is a list that contains nil like so.
attributsParam = [nil];
attributs = Array(attributsParam);
# [nil]
puts attributs.inspect
Simplest way to debug it is to add puts attributs.inspect
just before the loop.
Also consider if you really need the attributs = Array(attributsParam)
line or if it's already something Enumerable.
in `_main': undefined method `run' for nil:NilClass (NoMethodError)
At the point where you call request.run
the value for request
is nil
. This is why you are seeing the error you're given.
This is happening because the line right above it assigns the nil
value to the request
variable.
You are clearly coming from another language that is not Ruby (some type of C maybe?), by how you've formatted things. It would help for you to get more familiar with Ruby and its idioms. However, best I can tell, you want to do something like this instead:
def _main
request = MySqliteRequest.new
request.from('nba_player_data.csv')
request.select('name')
request.where('birth_state', 'Indiana')
request.run
end
_main()
This assumes you've also defined (and in some cases probably overridden) these methods on your MySqliteRequest
Object or Model:from
select
where
However, please note that the way you're going about this is just completely against how Ruby and Ruby on Rails is designed to work.
Ruby Error: nil can't be coerced to Integer
Silvio Mayolo doesn't explain error
Problem with changing instance variable -- is just one of the problem. But reason is another
For example this code:
class Foo
attr_accessor :bar
def initialize
@bar = 0
end
def baz
p x
10.times do
if bar < 6
@bar += 1
end
end
end
end
Foo.new.baz
will raise
undefined local variable or method `x'
but this code:
class Foo
attr_accessor :bar
def initialize
@bar = 0
end
def baz
10.times do
if bar < 6
x = 1
@bar += 1
else
p x
end
end
end
end
Foo.new.baz
will print
nil
nil
nil
nil
So factors_list[-1] - idx < 0
in your code raises error. Local variable idx
is is declared, but not initialized, because those if
branch is not executed
I am very surprised why your question is downvoted. The feeling that readers have not figured out the question, as well as Silvio Mayolo
What does the 'undefined method `+' for nil:NilClass (NoMethodError)' error in my ruby code mean?
The function only works 'a'..'z'
as @Jeremty mentioned, so W
and !
will be nil
.If you want to keep every none alphabet char, the following code maybe help.
def caesar_cipher(string, num)
alphabet = [*'a'..'z', *'A'..'Z']
caesar = ""
string.each_char do |letter|
old_idx = alphabet.find_index(letter)
if old_idx.nil?
caesar += letter
else
new_idx = (old_idx + num) % alphabet.count
caesar += alphabet[new_idx]
end
end
caesar
end
puts caesar_cipher("What a string!",5)
Why does defined input variable return nil after exception occurs?
I'm not sure this is what you want but I try
input = gets.chomp
begin
number = Integer(input)
puts "your number plus five: #{number + 5}"
rescue ArgumentError
puts "#{input} is not a valid number"
end
Comparison of fixnum with nil failed, value not nil
when it runs it gives an error that Fixnum can not be compared with nil and I have no idea why
It's because of this expression:
until (arr[idx] < arr[i]) || (i == arr.length)
Ruby evaluates it from left to right, i.e.:
arr = [2, 8, 4, 3]
idx = 2
i = 4
until (arr[idx] < arr[i]) || (i == arr.length)
# arr[ 2 ] < arr[4]
# 4 < nil
# ArgumentError
You can fix it by exchanging both checks:
until (i == arr.length) || (arr[idx] < arr[i])
# 4 == 4
# true
Ruby doesn't evaluate the right hand side because of short-circuit evaluation.
You're not asking for a different approach, but I couldn't resist to find a more compact solution. Here's my attempt:
We have to compare the value at the starting index n
with its adjacent values, i.e.
- compare
array[n]
toarray[n - 1]
- compare
array[n]
toarray[n + 1]
- compare
array[n]
toarray[n - 2]
- compare
array[n]
toarray[n + 2]
- ...
I would start by writing a method that returns the array of adjacent indices in alternating order, starting at n
, i.e. [n - 1, n + 1, n - 2, n + 2, ...]
:
def adjacent_indices(size, n)
(1...size).flat_map { |i| [n - i, n + i] }.reject { |i| i < 0 || i >= size }
end
flat_map
returns the aforementioned array. reject
is a bounds check, it removes all indices that are below 0
or above the array's size
.
Example:
adjacent_indices(5, 0) #=> [1, 2, 3, 4]
adjacent_indices(5, 1) #=> [0, 2, 3, 4]
adjacent_indices(5, 2) #=> [1, 3, 0, 4]
adjacent_indices(5, 3) #=> [2, 4, 1, 0]
adjacent_indices(5, 4) #=> [3, 2, 1, 0]
That looks good.
Using Enumerable#find
, we can easily find the first index i
whose array value (i.e. array[i]
) is larger than the value at index n
(i.e. array[n]
):
def nearest_larger(array, n)
adjacent_indices(array.size, n).find { |i| array[i] > array[n] }
end
Example:
# 0 1 2 3
a = [2, 8, 4, 3]
nearest_larger(a, 0) #=> 1
nearest_larger(a, 1) #=> nil
nearest_larger(a, 2) #=> 1
nearest_larger(a, 3) #=> 2
Rails 4: model.where.not does not return nil records
You were on the right track with the last query.
Book.where(category_id: 10).where("author != ? OR author IS NULL", "John Doe")
This should do what you are asking.
Side note, in Rails 5, you can use or
with ActiveRecord
queries, so you could so something like:
Book.where(category_id: 10).where.not(author: 'John Doe').or(where(author: nil))
Though I'd argue, in this case, the first query is clearer.
Comparison of Integer with nil failed (ArgumentError) while solving Insertion Sort with Ruby
Thanks for the clarification in the comments. I see the problem now.
In the swap algorithm here
elsif list[i] > list[i+1] && i > 0
len = (list[0..(i+1)].length)
list2 = list[0..(i+1)]
list = list - list2
count = 0
while count <= len+1
...
you are trying to split the array in two. You get list2
which is the first half of the array and then try and get the second half by subtracting list2
from list
.
The problem with using subtract here is that if you have duplicates it will remove them and make your lists too short.
In the example [3790,1,780,55,23,50,1111,60,50]
you should have a 50
in the first array and a 50
in the second half.
But using subtract removes one of those 50
.
When you add the two temporary lists back together you are now one element short (the missing 50
) and you get an out of bounds error when you get to the end of the array and try and access this 9th element which no longer exists.
Instead of using subtract here simply use the same method you used to make list2
.
list2 = list[0..(i+1)] # All elements in list from position 0 to i+1
list = list[(i+2)..-1] # All elements in list from position i+2 to end of list
Now list
and list2
are just the original list split, and when you add them back together are the end they should be the same length
def insertion_sort(list)
num = list.length
for i in (0..(num-2))
if list[i] > list[i+1] && i == 0
list[i], list[i+1] = list[i+1], list[i]
i+=1
elsif list[i] == list[i+1]
i+=1
elsif list[i] > list[i+1] && i > 0
len = (list[0..(i+1)].length)
list2 = list[0..(i+1)]
list = list[(i+2)..-1]
count = 0
while count <= len+1
if list2[len-1] < list2[len-2]
list2[len-2],list2[len-1]= list2[len-1],list2[len-2]
elsif list2[len-1] == list2[len-2]
count+=1
len-=len
else
count+=1
len-=1
end
end
list = list2 + list
end
end
list
end
p insertion_sort([2,1,4,8,7,3,100,99,8])
p insertion_sort([2,1,4,8,8,7,3,100,99])
p insertion_sort([3790,780,780,1,55])
Related Topics
Web Page Scraping Gems/Tools Available in Ruby
Ruby Equivalent of C#'s 'Yield' Keyword, Or, Creating Sequences Without Preallocating Memory
Ruby Installation (2.2.2) Fails in MACos Big Sur
Installing Ncurses for Ruby on Windows
Google Analytics API Error "Selected Dimensions and Metrics Cannot Be Queried Together."
Rails Gem to Break a Paragraph into Series of Sentences
Compare the Content, Not the Results, of Procs
Accessing JSON Objects in Ruby
Ruby on Rails How to Deal with Nan
How to Define a Method in Ruby Using Splat and an Optional Hash at the Same Time
Why Does the Break Statement in Ruby Behave Differently When Using Proc.New V. the Ampersand Sign
Ruby's Argv Can Be Empty on Windows Depending on a Way to Run Script
Generic Way to Replace an Object in It's Own Method
Ruby + Tk Command Binding - Scope Issue
Creating a Gmail Draft with Recipients Through Gmail API
Triple Single Quote VS Triple Double Quote in Ruby
Ruby on Rails: Creating a Model Entry with a Belongs_To Association