Problem with tuple add method

values = [1,2,3,4]

t= Tuple.new()
values.each { |val|
  puts val
  t = t + { val }
}

Error: tuple size cannot be greater than 300 (size is 301) ?
/usr/share/crystal/src/tuple.cr:80:17
What does this error mean ?
Crystal 0.36.1 [c3a3c1823] (2021-02-02)
LLVM: 10.0.0
Default target: x86_64-unknown-linux-gnu

It means there is a hard limit on tuple size: crystal/src/compiler/crystal/semantic/bindings.cr at d09d9e75716b35391e3e0ed5a4dbf112661fad05 · crystal-lang/crystal · GitHub

That was a fix for Error on ever increasing tuple · Issue #3816 · crystal-lang/crystal · GitHub

ok, but I am just putting 4 integers into a tuple

This part is kinda strange. However, do you really need to use a tuple in the first place? Tuples are meant to be immutable not built out dynamically. Either just define the tuple with your values statically, or use an array if you need to add values dynamically.

I.e. you could do like

t = {1, 2, 3, 4}

Yes, you are. The compiler doesn’t know that, though. All it sees is this:

  • t is initially an empty tuple
  • {val} is a tuple of one element
  • the result of t + {val} is a tuple that has the size of t + 1
  • this happens in a loop, so now you start from point one where t has one element
  • the compiler doesn’t know how many times this loop will happen so it considers all possibilities (infinite possibitilies) and hits the tuple limit

I think you want this:

values = [1, 2, 3, 4]

t = Tuple(Int32, Int32, Int32, Int32).from(values)
4 Likes

If you need to construct a tuple dynamically, you shouldn’t use a tuple.

2 Likes