Skip to content

replace does not handle multiple patterns for String #35327

@Keno

Description

@Keno
julia> replace("Keno", 'e'=>"abc", 'f'=>'g', 'a'=>'z')
ERROR: MethodError: no method matching similar(::String, ::Type{Any})
Closest candidates are:
  similar(::Array{T,1}, ::Type) where T at array.jl:357
  similar(::Array{T,2}, ::Type) where T at array.jl:358
  similar(::Array, ::Type, ::Tuple{Vararg{Int64,N}}) where N at array.jl:360
  ...
Stacktrace:
 [1] _similar_or_copy(::String, ::Type{Any}) at ./set.jl:415
 [2] replace(::String, ::Pair{Char,String}, ::Vararg{Pair,N} where N; count::Nothing) at ./set.jl:530
 [3] replace(::String, ::Pair{Char,String}, ::Pair{Char,Char}, ::Pair{Char,Char}) at ./set.jl:527
 [4] top-level scope at REPL[12]:1

This is surprising, because it doesn't match the API of replace on generic collections:

julia> replace([1,2,3],1=>4,2=>5,3=>6)
3-element Array{Int64,1}:
 4
 5
 6

Now, replace on string is a bit special, because it can take Strings and Regexes also, as patterns, and perhaps we should only allow a single pattern for those cases (because otherwise the order of replacements is ambiguous), but I think it should work for Char, and at least give a better error message for multiple patterns of another type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions