IT

Ruby Strings의 gsub 메소드와 하위 메소드의 차이점은 무엇입니까?

lottoking 2020. 8. 20. 19:06
반응형

Ruby Strings의 gsub 메소드와 하위 메소드의 차이점은 무엇입니까?


나는 String오늘 문서를 읽어 보았고, :sub전에는 본 적이없는 방법을 보았다 . 나는 사용 :gsub하고있는 것과 동일한 사운드입니다. 누구든지 나에게 차이점을 설명 할 수 있습니까? 감사합니다!


g전 세계적으로 (모든) 대체 같이 세계를 의미합니다 :

irb에서 :

>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"

차이점은 sub지정된 패턴의 첫 번째 발생 만 대체하는 반면 gsub모든 발생에 대해 수행한다는 것입니다 (즉, 전체적으로 대체 됨).


value = "abc abc"
puts value                                # abc abc
# Sub replaces just the first instance.
value = value.sub("abc", "---")
puts value                                # --- abc
# Gsub replaces all instances.
value = value.gsub("abc", "---")
puts value                                # --- ---

subgsub모든 일치 교환을 수행한다.

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)


sub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )  
##"An Introduction to R Software Course will be of 8 weeks duration"

gsub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"

참고 URL : https://stackoverflow.com/questions/6766878/what-is-the-difference-between-gsub-and-sub-methods-for-ruby-strings

반응형