[ruby] or equals 기능 - ||=

Ruby 2016. 8. 17. 21:03



특정 변수가 정의되지 않았다면, 값을 저장하는 코드가 있다고 가정한다.

아마도 c/c++/java에 익숙한 개발자라면, 다음과 같이 코드를 짤 수 있다. 


xx = 3
unless defined? xx
xx = [1,2,3].inject(0) { |sum, t| sum + t }
end
puts xx


ruby에서는 or equals 라는 ||=를 사용하면, if 또는 unless 문 없이 쉽게 한 줄로 구현할 수 있다. 


xx = 3
xx ||= [1,2,3].inject(0) { |sum, t| sum + t }
puts xx


Posted by '김용환'
,



숫자, 문자에 대해서 교집합, 합집합, -집합(supplement) 기능을 사용할 수 있다.



a = [1, 2, 3, 4, 5]

b = [4, 5, 6, 7, 8]

puts "a-b (int) : " + (a - b).map { |s| "#{s}" }.join(' ')



a = ["1", "2", "3", "4", "5"]

b = ["4", "5", "6", "7", "8"]

puts "a-b : " + (a - b).map { |s| "#{s}" }.join(' ')

puts "b-a : " + (b - a).map { |s| "#{s}" }.join(' ')

puts "(a-b) || (b-a) : " + (a- b | b - a).map { |s| "#{s}" }.join(' ')





<결과>

a - b (int) : 1 2 3

a-b : 1 2 3

b-a : 6 7 8

(a-b) || (b-a) : 1 2 3 6 7 8




Posted by '김용환'
,

[ruby] 타입(type) 알기

Ruby 2016. 8. 17. 14:18



ruby에서 타입을 확인하고 싶다면, .class를 호출한다.


require 'redis'


...

redis = Redis.new(TEST_REDIS)
result = redis.hgetall("test")
if (result.nil?)
return nil
end

puts result.class

ruby hash를 리턴한다.


<결과>

Hash








Posted by '김용환'
,



OS El Capitan(10.11.6)에서 Xcode 7.3.1를 설치한 후, ruby thrift 모듈이 컴파일이 실패했다.



$ sudo gem install thrift


compiling compact_protocol.c

compact_protocol.c:442:41: error: shifting a negative signed value is undefined [-Werror,-Wshift-negative-value]

    rb_exc_raise(get_protocol_exception(INT2FIX(-1), rb_str_new2(but)));

....



xcode 설치 디렉토리 정보는 다음과 같다. (뒷 부분에서 바꾼다).


$xcode-select -p

/Applications/Xcode.app/Contents/Developer




https://developer.apple.com/download/more/ 에 접속하고, 로그인 한 후, 

Command Line Tools OS X 10.11 for Xcode 7.2 설치 파일을 다운받고 설치한다.






OS X 10.11 for Xcode 7.2의 커맨드 라인의 위치를 변경한다.


$ sudo xcode-select -s /Library/Developer/CommandLineTools/



바뀐 xcode 커맨드 라인을 확인한다.


$ xcode-select -p

/Library/Developer/CommandLineTools




$ gem install thrift 를 실행한다. 


더 이상 shifting a negative signed value is undefined [-Werror,-Wshift-negative-value] 에러는 발생하지 않는다.

Posted by '김용환'
,