1

I'm trying to replace some characters in a String From a map

Case 1

​map= ['O':'0', 'L':'1', 'Z':'2', 'E':'3']
"Hey".toUpperCase().toCharArray().each{
         print map.get(it,it)
     }

The result is

HEY

Case 2 : I dont use toCharArray()

"Hey".toUpperCase().each{
        print map.get(it,it)
    }

The result is like expected

H3Y

So I tried several alternatives when using toCharArray(), and the only way to access the value is to use map."$it"

Why i can only use map."$it" to access my map when using toCharArray() ?

Nouaman Harti
  • 213
  • 2
  • 4
  • Not answering te question, but an alternative is `map = ['O':'0', 'L':'1', 'Z':'2', 'E':'3'].withDefault { it } ; println "Hey".toUpperCase().collect { map[it] }.join()` – tim_yates Sep 24 '15 at 09:32

1 Answers1

4

Because you are trying to get a value from a map using a char whilst every key there are String, and they are not equals:

assert !'E'.equals('E' as char)

$it works because it is converted to String:

e = 'E' as char

assert "$e".toString().equals('E')

(Note the toString() is needed, otherwise the comparison will happen between String and GStringImpl which are not equals)

Will
  • 14,348
  • 1
  • 42
  • 44