Crystal: Allow accessing named tuples with strings

Created on 7 Jul 2016  路  3Comments  路  Source: crystal-lang/crystal

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

accepted stdlib

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:

"foo bar".gsub o: 'x', a: 'y' # => "fxx byr"
sprintf "change %{this}", this: "that" # => "change that"

In this way some memory allocation is avoided.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

paulcsmith picture paulcsmith  路  3Comments

asterite picture asterite  路  3Comments

relonger picture relonger  路  3Comments

Sija picture Sija  路  3Comments

cjgajard picture cjgajard  路  3Comments