I’d like to be able to check if an array was defined, at run time, before I start adding to it or decide to run a constructor. Is it possible in Crystal?
I come across this post, but seems that this idea have been abandoned.
I’d like to be able to check if an array was defined, at run time, before I start adding to it or decide to run a constructor. Is it possible in Crystal?
I come across this post, but seems that this idea have been abandoned.
Can you share some example code of what you’re wanting to do? It’s probably enough to just make sure it’s not nil
, or more ideally make it not possible to be nil
so you can avoid having to handle checking in the first place.
But filling an array with nil
s before initialization requires me to know it’s size.
So for an example, if I was to parse some user data, where I have no way to know how big it is or how long am I about to parse it, is it currently possible? Just checking if the value is falsy in that hash bellow gives me a KeyError
, so I can not even access the array to check it’s value.
def make_stacks(raw_data)
stacks = Hash(Int32, Array(Char)).new
char = raw_data.each_char
(0...raw_data.size).each_slice(4) do |slice|
item = char.next
next if item == ' '
id = (x = ((((slice[-1] + 1) / 4)).to_i % 9)) == 0 ? 9 : x
if !stacks[id]
stacks[id] = [] of Char
end
stacks[id].push item.as(Char)
end
stacks
end
Ok… wait, should I just be checking for exception?
Ah okay, so you have a few options in this case.
stacks.has_key? id
which will return false
if the hash doesn’t have that ID as a key. Which would then allow your logic to create the empty array for the id.||=
to allow inlining it all. E.g. (stacks[id] ||= [] of Char) << item.as Char
stacks = Hash(Int32, Array(Char)).new { |hash, key| hash[key] = [] of Char }
# ...
# Can skip checking if it has the key in the first place.
stacks[id] << item.as Char