Matthew Kerwin wrote in post #1139645:
> \1 isn't a variable name, it's a string escape sequence. It will only
> work
> inside a string. Try either map['\1']

map = { "arup" => "1989"}
puts "arup rakshit".gsub(/(arup)\s+rakshit/, map['\1'] )
# ~> -:2:in `gsub': no implicit conversion of nil into String 
(TypeError)
# ~>   from -:2:in `<main>'

or map[$1]

map = { "arup" => "1989"}
puts "arup rakshit".gsub(/(arup)\s+rakshit/, map[$1] )
# ~> -:2:in `gsub': no implicit conversion of nil into String 
(TypeError)
# ~>   from -:2:in `<main>'

$1,$2 etc work with blocks.

>
> (I just woke up so my head may still be cloudy.)


My question is when the below is working :

map = { "arup" => "1989"} # !> assigned but unused variable - map
puts "arup rakshit".gsub(/(arup)\s+rakshit/, '<\1>' )
# >> <arup>

Why not below ?

map = { "arup" => "1989"}
puts "arup rakshit".gsub(/(arup)\s+rakshit/, map['\1'] )
# ~> -:2:in `gsub': no implicit conversion of nil into String 
(TypeError)
# ~>   from -:2:in `<main>'

-- 
Posted via http://www.ruby-forum.com/.