Reputation: 10419
I have a String variable c
that I want to set in a map.
def c = "tony"
def methinks = [c:"bb"]
I want methinks[tony] = "bb"
but I get
methinks[c] = "bb"
Any tips
Upvotes: 1
Views: 69
Reputation: 2789
You can access map values with dot notation or with []
. It seems that you've mixed it up :) You can do it like below:
def methinks = [:]
c = "tony"
methinks."$c" = "bb"
assert methinks."$c" == "bb"
or:
def methinks = [:]
c = "tony"
methinks[c] = "bb"
assert methinks[c] == "bb"
As you can see the second version looks definitely better.
After question update: You're still mixing notations but @Opal provided exact solution to your problem.
Upvotes: 4
Reputation: 84756
It all works as expected:
def methinks = [:]
c = "tony"
methinks[c] = "bb"
assert methinks.tony == "bb"
After question update:
You need to escape c
variable because it will be treated literally (as c
sign)
See:
def c = "tony"
def methinks = [(c):"bb"]
assert methinks.tony == 'bb'
Upvotes: 4