Return empty array (Ruby)
To fix your code, change what you have to one of the following:
num.nil? || num.empty? ? [] : num.sort
num.nil? ? [] : num.sort
(num || []).sort
num.to_a.sort
The latter two convert num
to an empty array if num
is nil
, then sort the result. See NilClass.to_a.
#scan suddenly returns an empty array
From the scan
docs.
If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group.
By adding the parentheses to the middle of your regex, you created a capturing group. Scan will return whatever that group captures. In the example you gave, it will be 'u'
.
"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".scan(/\A\w+(\s|\w)\w+/) #=> [["u"]]
The group can be marked as non-capturing to return to your old implementation
"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".scan(/\A\w+(?:\s|\w)\w+/) #=> ["Rahul"]
# ^
Or you can add a named capture group to what you actually want to extract.
"Rahul\n \n\n \n Nov 6\n\n\n ・2 min read".match(/\A(?<name>\w+(\s|\w)\w+)/)[:name] #=> "Rahul"
Should Ruby method return nil or empty object
Not only in ruby but also in other languages, you should return an empty enumerable/collection. There is no need for your users to check if the return value is nil or not before doing any action, it's a waste of time.
Why does .all? return true on an empty array?
In Ruby you can never loop over an empty collection (array, hashes, etc.), so in your case your block never gets executed. And if the block never gets executed, all?
returns true (there is no condition to make the result false).
Read about all?
in the Ruby documentation.
You can simply achieve your goal by
!array.empty? && array.all? { |value| value == 2 }
Slicing based on a condition, else return empty array
You can use the array's size as a fallback:
arr[(indices.max || arr.size)..-1]
Pushing objects into an array is returning an empty array
Adding an instance variable queue
to the board class solved this
class Board
def initialize(live_cell_count, queue)
@live_cell_count = live_cell_count
@queue = queue
end
def queue
@queue
end
Inserting queue.push(cell)
in the conditional successfully appends each cell to the queue
array.
def rules(cell)
if something
cell.queue_for_birth
@queue.push(cell)
else something_else
cell.queue_for_death
@queue.push(cell)
end
end
Why does Ruby Array slicing sometimes returns nil and sometimes returns empty Array?
The first parameter of Array#slice(start,length) is the place between indices where slicing should begin :
array = [1, 2, 3, 4]
# elements : [ 1 2 3 4 ]
# ↑ ↑ ↑ ↑ ↑
# slice start indices : 0 1 2 3 4
slice(0,_)
begins left of 1
, slice(3,_)
begins left of 4
, and slice(4,_)
begins at the last possible place : right of 4
.
slice(4,0)
is still inside array
, it's the empty Array right of 4
.
slice(5,0)
isn't inside array
anymore, it's nil
.
Split doesn't return empty string
From the docs:
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is
1
, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
And so:
"[][][]".split("[]", -1)
# => ["", "", "", ""]
This yields four empty strings rather than your three, but if you think about it it's the only result that makes sense. If you split ,,,
on each comma you would expect to get four empty strings as well, since there's one empty item "before" the first comma and one "after" the last.
Related Topics
What Are the Differences Between Rbenv, Rvm, and Chruby
Ruby: Module, Require and Include
Active Admin: Customize Only New Form
Rails: Hasmanythroughassociationnotfounderror
Rails: Testing Named Scopes with Rspec
Why Should I Care About Rvm's Gemset Feature When I Use Bundler
Can Someone Explain Ruby's Use of Pipe Characters in a Block
Setting Up the Logger in Rails 3
Rails 4 Error R14 on Heroku (Memory Quota Exceeded)
Ruby/Rails - Models Named with Two Words (Naming Convention Issues)
How to Set Ruby's Load Path Externally
Rails If Object.Nil? Then Magic '' in Views
Are There Any Ipython-Like Shells for Ruby or Rails
Engine's Assets with Rails 3.1
How to Calculate the Offset, in Hours, of a Given Timezone from Utc in Ruby