Error in type expecting NamedTuple Tuple but I need a variable hash

28 views
Skip to first unread message

Miguel Michelsongs

unread,
Oct 12, 2018, 7:11:40 PM10/12/18
to Crystal
Hello guys, i'm just beginning with Crystal. pure awesomeness!

I'm implementing a class with receives a hash option and I initializing some instance variables, here is the code


  class Command
    @command : String
    @target : String
    @options : Hash(Symbol, String)
    def initialize(options = {} of Symbol => String)
      puts options
      @command = options["command"]
      @target  = options["target"]
      @options = options["options"]
    end
end
 
Command.new({
    command: "one", 
    target: "two", 
    options: {message: "he"}
})

error is in line 11: instance variable '@options' of Command must be Hash(Symbol, String), not NamedTuple(message: String)

so, if I change type definition to NamedTuple(message: String) it works , but the options k , v may vary, ¿how could I tackle this to accept any Hash(k,v)?

best regards to the community




Brian J. Cardiff

unread,
Oct 13, 2018, 12:04:53 AM10/13/18
to crysta...@googlegroups.com

Hi Miguel,

The expression

{
    command: "one", 
    target: "two", 
    options: {message: "he"}
}

is of type NamedTuple(command: String, target: String, options: NamedTuple(message: String))

And the expression

{
    :command => "one", 
    :target => "two", 
    :options => {:message => "he"}
}

is of type Hash(Symbol, Hash(Symbol, String) | String)

In this case, since each key may have different value types associated I would recommend to take advantage of NamedTuples since they will preserve the type information for each key.

I hope this help to move forward.


--
You received this message because you are subscribed to the Google Groups "Crystal" group.
To unsubscribe from this group and stop receiving emails from it, send an email to crystal-lang...@googlegroups.com.
To post to this group, send email to crysta...@googlegroups.com.
Visit this group at https://groups.google.com/group/crystal-lang.
To view this discussion on the web visit https://groups.google.com/d/msgid/crystal-lang/544cc844-c925-451a-ab4c-54a11b1aa53f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Brian J. Cardiff
[email] bcar...@manas.tech
[web] https://manas.tech
Reply all
Reply to author
Forward
0 new messages