2016-06-24 8 views
3

< < + =의 차이점을 읽었습니다. 그러나 나는 내 기대 된 코드가 내가 원하는 것을 출력하지 않기 때문에이 차이점을 이해하지 못할 수도 있다고 생각한다. Ruby differences between += and << to concatenate a string I는 문자/단어의 배열에 "고양이"해독 할루비 연산자 혼동 삽 (<<) 및 + =, 배열 배열

에 응답

=> [ "C", "카", "고양이", "A", "시" 온도 < < 단어 [j]가 이 특정한 경우에 내 논리가 나에게 때 온도 + = 단어 [J] 다른 올바른지 이유, "t"]

def helper(word) 
words_array = [] 
idx = 0 
while idx < word.length 
    j = idx 
    temp = "" 
    while j < word.length 
     **temp << word[j]** 
     words_array << temp unless words_array.include?(temp) 
    j += 1 
    end 
    idx += 1 
end 
p words_array 
end 
helper("cat") 

는 이해가 안 돼요.

답변

3

한 가지 차이점은 장소에 << 작품 때문에 다소 빠른 +=보다 때문이다. 다음 코드

require 'benchmark' 

a = '' 
b= '' 

puts Benchmark.measure { 
    100000.times { a << 'test' } 
} 

puts Benchmark.measure { 
    100000.times { b += 'test' } 
} 

내가 원래 질문을 오해 업데이트

0.000000 0.000000 0.000000 ( 0.004653) 
0.060000 0.060000 0.120000 ( 0.108534) 

산출한다. 여기에 무슨 일이 있습니다. Ruby 변수는 객체 자체가 아닌 객체에 대한 참조 만 저장합니다. 동일한 코드를 사용하여 동일한 문제를 해결할 수 있습니다. 루프의 반복마다 tempwords_array을 인쇄하라고했습니다.

temp: c 
words: ["c"] 
temp: ca 
words: ["ca"] 
temp: cat 
words: ["cat"] 
temp: a 
words: ["cat", "a"] 
temp: at 
words: ["cat", "at"] 
temp: t 
words: ["cat", "at", "t"] 
["cat", "at", "t"] 

당신이 볼 수 있듯이, 첫 번째, 루비는 단순히 words_array의 마지막 요소를 교체 한 후 내부 루프의 각 반복시 : 여기

def helper(word) 
    words_array = [] 

    word.length.times do |i| 
    temp = '' 
    (i...word.length).each do |j| 
     temp << word[j] 
     puts "temp:\t#{temp}" 
     words_array << temp unless words_array.include?(temp) 
     puts "words:\t#{words_array}" 
    end 
    end 

    words_array 
end 

p helper("cat") 

는 인쇄 것입니다. words_arraytemp이 참조하는 문자열 객체에 대한 참조를 보유하고 있고 <<이 새 객체를 만드는 대신 해당 객체를 수정하기 때문입니다.

외부 루프 temp의 각 반복마다 새 개체가 설정되고 해당 개체는 words_array에 추가되므로 이전 요소가 대체되지 않습니다.

+= 구문은 내부 루프의 각 반복마다 temp에 새 개체를 반환하므로 예상대로 작동합니다.

+0

여기 정확히 같은 것을 비교하지 않습니까? –

+0

감사합니다. @ sagarpandya82. 나는 그것을 고쳤다. – lwassink

+0

나는 셔블 방법을 사용하는 것이 더 빠르다는 것에 동의하지만, 내게 맞는 논리가 있기 때문에 셔블 대 + =가 다른 이유를 궁금해했다. – DanielSD

2

temp << word[j]temp inplace를 수정합니다.

temp = temp + word[j]의 약자 인 temp += word[j]은 다른 개체를 만들고 temp 변수에 할당합니다. BTW

:

input = 'cat'.split('') 
(1..input.length).each_with_object([]) do |i, memo| 
    memo << input.each_cons(i).to_a 
end.flatten(1).map(&:join) 
#⇒ [ 
# [0] "c", 
# [1] "a", 
# [2] "t", 
# [3] "ca", 
# [4] "at", 
# [5] "cat" 
# ] 
2
# this code might be easier to follow 
word = "cat" 

def helper(word) 
    letter_array = [] 
    copy_cat = word 
    word.length.times do 
    starts = 0 
    ends = 0 
    loop do 
     letter_array << copy_cat[starts..ends] 
     ends += 1 
     break if ends == copy_cat.length 
    end 
    copy_cat.delete!(word[0]) 
    end 
    letter_array 
end 

p helper(word) # returns ["c", "ca", "cat", "a", "at", "t"]