developer tip

Ruby에서 <<는 무엇을 의미합니까?

copycodes 2020. 12. 10. 20:42
반응형

Ruby에서 <<는 무엇을 의미합니까?


코드가 있습니다.

  def make_all_thumbs(source)
    sizes = ['1000','1100','1200','800','600']
    threads = []
    sizes.each do |s|
      threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }
    end
  end

무슨 <<뜻이야?


일반적인 방법으로 '<<'

대부분의 경우 '<<'는 나머지와 같이 정의 된 메서드이며, 귀하의 경우에는 "이 배열의 끝에 추가"를 의미합니다 ( 여기 참조 ).

그것은 당신의 특별한 경우이지만 "<<"메소드를 만나게 될 다른 많은 경우도 있습니다. 나는 그것을 '연산자'라고 부르지 않을 것이다. 이것은 실제로 당신이 재정의하거나 당신 자신의 개체를 위해 구현 될 수있는 어떤 개체에 정의 된 메서드이기 때문이다. '<<'의 다른 경우

  • 문자열 연결 : "a"<< "b"
  • IO에 출력 쓰기 : io << "텍스트 줄 \ n"
  • 메시지 다이제스트, HMAC 또는 암호에 데이터 쓰기 : sha << "Text to be hashed"
  • OpenSSL :: BN의 왼쪽 이동 : bn << 2
  • ...

싱글 톤 클래스 정의

그런 다음 프로그램 흐름 내에서 현재 범위의 신비한 변화 (= 자기의 변화)가 있습니다.

class A
  class << self
    puts self # self is the singleton class of A
  end
end

a = A.new
class << a
  puts self # now it's the singleton class of object a
end

그 수수께끼 class << self로 인해 내부에 대해 궁금해하고 조사했습니다. 내가 언급 한 모든 예제에서 <<실제로는 클래스에 정의 된 메서드입니다.

obj << stuff

다음과 같다

obj.<<(stuff)

class << self구조 (자기 대신에 또는 객체) 정말 다르다. 그것은 실제로 언어 자체의 내장 기능입니다. CRuby에서는 parse.y 에서 다음 과 같이 정의 됩니다.

k_class tLSHFT expr

여기서 tLSHFT는 '<<'토큰이고, k_class는 'class'키워드이며 expr은 임의의 표현식입니다. 즉, 실제로 쓸 수 있습니다.

class << <any expression>

식 결과의 싱글 톤 클래스로 '시프트'됩니다. tLSHFT 시퀀스는 'NODE_SCLASS'표현식으로 구문 분석되며 이는 싱글 톤 클래스 정의 (참조 : node.c)라고합니다.

case NODE_SCLASS:
    ANN("singleton class definition");
    ANN("format: class << [nd_recv]; [nd_body]; end");
    ANN("example: class << obj; ..; end");
    F_NODE(nd_recv, "receiver");
    LAST_NODE;
    F_NODE(nd_body, "singleton class definition");
    break; 

여기 문서

그리고 어떻게 잊을 수 있겠습니까? Here Documents 는 다시 완전히 다른 방식으로 '<<'를 사용합니다. 다음을 선언하여 편리하게 여러 줄에 걸쳐있는 문자열을 정의 할 수 있습니다.

here_doc = <<_EOS_
The quick brown fox jumps over the lazy dog.
...
_EOS_

'here doc 연산자'를 구별하려면 임의의 문자열 구분 기호가 '<<'바로 뒤에 와야합니다. 해당 초기 구분 기호와 동일한 구분 기호의 두 번째 발생 사이의 모든 것이 최종 문자열의 일부가됩니다. '<<-'를 사용할 수도 있습니다. 차이점은 후자를 사용하면 선행 또는 후행 공백을 무시한다는 것입니다.


배열 끝에 값을 추가하기 위해 배열에서 주로 사용됩니다.

a = ["orange"]
a << "apple"
puts a

이것을 준다

  [ "주황색", "사과"] 
결과.


새 항목 추가하여 기존 배열 을 공급할 수있는 연산자입니다 .

위의 예에서는 threads5 개의 새 스레드로 빈 배열 을 채 웁니다.


'a << b'는 a 끝에 b를 추가하는 것을 의미합니다.


In ruby you always have more the one way to do things. So, Ruby has some nice shortcuts for common method names. like this one is for .push instead of typing out the .push method name, you can simply use <<, the concatenation operator. in fact in some cases you can use any of these for the same operation .push and + with <<.

Like you can see in this example:

alphabet = ["a", "b", "c"]
alphabet << "d" # Update me!
alphabet.push("e") # Update me!
print alphabet 
caption = "the boy is surrounded by "
caption << "weezards!" # Me, too!
caption += " and more. " # Me, too!
# .push can no be uses for concatenate 
print caption

so you see the result is:

["a", "b", "c", "d", "e"]
the boy is surrounded by weezards! and more.

you can use the operator << to push a element into an array or to concatenate a string to another.

so, what this is this doing is creating a new element/object Thread type and pushing it into the array.

 threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }

In ruby '<<' operator is basically used for:

  1. Appending a value in the array (at last position)

    [2, 4, 6] << 8 It will give [2, 4, 6, 8]

  2. It also used for some active record operations in ruby. For example we have a Cart and LineItem model associated as cart has_many line_items. Cart.find(A).line_items will return ActiveRecord::Associations object with line items that belongs to cart 'A'.

Now, to add (or say to associate) another line_item (X) to cart (A),

Cart.find(A).line_items << LineItem.find(X)
  1. Now to add another LineItem to the same cart 'A', but this time we will not going to create any line_item object (I mean will not create activerecord object manually)

    Cart.find(A).line_items << LineItem.new

In above code << will save object and append it to left side active record association array.

And many others which are already covered in above answers.

참고URL : https://stackoverflow.com/questions/6852072/what-does-mean-in-ruby

반응형