How to append a key to a NamedTuple, dependent on an if condition?

Example code: (with comments):
https://play.crystal-lang.org/#/r/6k7q/edit

def send_to_players(data, cmd)
  puts data
  puts cmd
end


if rand < 0.9
# append a key called "item" to the NamedTuple ({}) below, but how?

end

send_to_players ({id: 1}), "HIT_OBJ"

I was thinking of something like this, but this isn’t really “appending” a key. It’s just copying the line into a separate condition, but I guess it should be fine, or is there a more proper way?

if rand < 0.9
send_to_players ({id: 1}), "HIT_OBJ"
else
send_to_players ({item: 1, id: 1}), "HIT_OBJ"
end

NamedTuple#merge should work.

1 Like

I’m pretty sure you’ll have a lot of trouble trying to make that work. The answer is always: don’t use named tuples. Named tuples are meant to represent named arguments. Or small immutable data that’s a bit more clear than bare tuples. In your case you want a class with an optional item, it seems.

@asterite

Here is my send method for my Client class:

  def send(msg, cmd = "SERV")
    msg_buffer = {cmd: cmd, message: msg}
    new_message = msg_buffer.to_json
    socket.write_bytes(new_message.bytesize)
    socket.send new_message
  end

I have over 100 methods that all use
client.send ({custom_data: data, custom_data2: etc}), "CMD".
I have not run into any issues yet, but is this problematic?

You can use #merge with two NamedTuples to create a new one or, the better way, just use Hashes. There is no way to add a key to a NamedTuple though, as they are immutable.

1 Like

Wow, already 4 months. Wtf am I doing with my life.