I have a problem accessing a named tuple by using string literals, it seem the compiler is converting strings keys to symbols:
data = {"host": "23.216.10.10"}
data["host"]
=> no overload matches 'NamedTuple(host: String)#[]' with type String
Overloads are:
- NamedTuple(T)#[](key : Symbol)
This can be confirmed when inspecting data too:
p data
=> {host: "23.216.10.10"}
I am using OSX with Xcode 7.3.1 and Crystal 0.18.7
Yes, that's intentional so far. Though I think allowing named tuple key access by string would be convenient and we should allow it, for example when the key comes from an external source such as ARGV.
For now you can access your key with data[:host]
or data[:"foo bar"]
for whitespace containing keys.
Fine, i missed that! This make sense ;)
I was actually going to propose this some time ago but wasn't sure it was going to be liked.
I think a named tuple should be able to be indexed with a string literal, and char literals too. Some APIs can take advantage of this. For example:
"foo bar".gsub o: 'x', a: 'y' # => "fxx byr"
sprintf "change %{this}", this: "that" # => "change that"
In this way some memory allocation is avoided.
Most helpful comment
I was actually going to propose this some time ago but wasn't sure it was going to be liked.
I think a named tuple should be able to be indexed with a string literal, and char literals too. Some APIs can take advantage of this. For example:
In this way some memory allocation is avoided.