How to check if a variable is defined?

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.

1 Like

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 nils 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.

  1. Use 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.
  2. Can leverage ||= to allow inlining it all. E.g. (stacks[id] ||= [] of Char) << item.as Char
  3. Leverage Hash(K, V) - Crystal 1.7.2 to create an empty array for that key if it’s not already defined. E.g.
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
2 Likes