user738888
user738888

Reputation:

Passing in multiple data types in Ruby?

How do I pass in a Hash, String, Array and Symbol to a function in Ruby? I tried it this way:

func key: 'value', 'string', ['some', 'array'], :asymbol

This does not work.

Upvotes: 1

Views: 158

Answers (3)

Linuxios
Linuxios

Reputation: 35788

Your syntax is bad. Please use parenthesis and brackets:

func({key: "val"}, 'str', [1, 2], :sym)

Otherwise, the language is just seeing gibberish.

Upvotes: 0

maček
maček

Reputation: 77786

You need {} around the hash if there are other arguments that come after it.

# this will work
func({key: 'value'}, 'string', ['some', 'array'], :asymbol)

Because of this, it's very common to see hash types as the last argument in a method signature. Just update your method to accept the hash last.

# this will work, too
func 'string', ['some', 'array'], :asymbol, key: 'value'

Upvotes: 1

sgrif
sgrif

Reputation: 3822

You need to use brackets to pass additional params after a hash. They can only be implied for the last argument to a method.

func({key: 'value'}, 'string', ['some', 'array'], :asymbol)

Upvotes: 3

Related Questions