ruby 에서, 문자열에서 \r\n 또는 \t을 삭제하려면 두가지를 써야 한다. strip() 과  gsub()를 잘 쓰면 된다.



strip 사용 예제

>> "   string  ".strip

=> "string"

>> "\r\n\r\n string\t ".strip

=> "string"

>> "\r\n\r\n string \r\n test \t ".strip

=> "string \r\n test"

>>


gsub 사용 예제


?> "\r\n\r\n string \r\n test \t ".gsub(/\r/,"").gsub(/\n/,"")

=> " string  test \t "

>> "\r\n\r\n string \r\n test \t ".gsub(/\r/,"").gsub(/\n/,"").strip

=> "string  test"

>> "\r\n\r\n string \r\n test \t ".gsub(/\r/,"").gsub(/\n/,"").gsub(/\t/,"").strip

=> "string  test"






Posted by '김용환'
,



ruby에서 eval을 이용하면, 문자열 unicode code 값을 unicode 로 바꿀 수 있다. 


>> string="\\uc544\\ub2c8"

=> "\\uc544\\ub2c8"

>> string_to_eval = "\"#{string}\""

=> ""\\uc544\\ub2c8""

>> eval(string_to_eval)

=> "아니"




예제


CSV.foreach('test.csv', { :col_sep => ',' }) { |row| if (row[7].include?"http") ;  puts 1 ; else ;  string=row[7][13..-3] ; string_to_eval = "\"#{string}\"" ; m=eval(string_to_eval);puts m  ; end  }

Posted by '김용환'
,

[ruby] 역슬래쉬

Ruby 2015. 12. 10. 11:58


ruby의 역슬래쉬( \\)는 자바의 역슬래쉬(\\)와 거의 비슷하다.

항상 짝수로 써야 한다. \\는 one byte이다. 


>> "abc\\\\".size

=> 5

>> "abc\\\\".gsub("\\\\", "\\")

=> "abc\\"

>> temp="abc\\\\".gsub("\\\\", "\\")

=> "abc\\"

>> temp.size

=> 4



따라서 아래와 같이 \\ 를 \로 바꾸는 코드로 진행할 때 hang이 될 수 있다.


>> "abc\\".gsub("\\", "\")

(hang...)


Posted by '김용환'
,





ruby에서 특정 문자열이 주어진 문자열에 포함되었는지 확인하려면, include?를 사용한다.



>> a= "abc\\"

=> "abc\\"


>> if a.include?"abc"

>>   puts "OO"

>> end

OO




한 줄로 쓸려면, ; 을 사용할 수 있다. 


CSV.foreach('test.csv', { :col_sep => ',' }) { |row| if (row[7].include?"http") ;  puts row[7] ; end  }





Posted by '김용환'
,


substring 하려면 [StartIndex..EndIndex] 를 이용한다



>> abc

=> "abcd;;;;;efg=aaa:::::bbb"


>> abc[0..1]

=> "ab"




-1을 선택하면, 맨 마지막 문자 인덱스를 의미한다.


>> abc[4..-1]

=> ";;;;;efg=aaa:::::bbb"


>> abc[0..-1]


=> "abcd;;;;;efg=aaa:::::bbb"

>> abc[0..-2]


=> "abcd;;;;;efg=aaa:::::bb"


>> abc[0..-1]

=> "abcd;;;;;efg=aaa:::::bbb"


>> abc[0..0]

=> "a"


Posted by '김용환'
,


전체 문자열에 대해서 한번만 치환하려면 sub()를 사용하고, 전체 문자열에 대해서 치환하려면 gsub()를 사용한다.



ttt='"{\"contents\":\"\\uc544\\ub2c8"}"'



 ttt.sub('\\"', '"')

=> ""{"contents\\":\\"\\uc544\\ub2c8"}""



ttt.gsub('\\"', '"')

""{"contents":"\\uc544\\ub2c8"}""




------------


한 번에 두 번 이상의 단어를 치환하려면 배열 사용할 수 있다.



>> abc = 'abcd;efg=aaa:bbb'

=> "abcd;efg=aaa:bbb"


>> replacements.each {|replacement| abc.gsub!(replacement[0], replacement[1])}

=> [[";", ";;;;;"], [":", ":::::"]]


>> abc

=> "abcd;;;;;efg=aaa:::::bbb"

Posted by '김용환'
,



잘 동작하던 Ruby 시스템이 갑작스런 Gem 설치 이슈가 발생했다.


ruby/lib/ruby/gems/2.1.0/gems/activerecord-4.1.5/lib/active_record/connection_adapters/connection_specification.rb:190:in `rescue in spec': Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). (Gem::LoadError)




Gemfile에 아래와 같이 설정했었다.


gem 'activerecord', '4.1.5'

gem 'mysql2'


그래서 기존에 돌던 버전 정보를 맞춰(version specifier) 해결했다.


gem 'activerecord', '4.1.5'

gem 'mysql2', '0.3.20'




이 과정에서 공부한 version specifier를 확인했다.


예)

0.3.0 이라고 사용하면 0.3.0 버전만 사용한다.

>= 0.3.0 이라고 사용하면 0.3.0 이상만 되게 한다.

~> 0.3.1 이라고 하면 0.3.1 부터 0.4.0 이하 버전만 쓸 수 있게 한다.



'Ruby' 카테고리의 다른 글

[ruby] string에서 substring하기  (0) 2015.12.09
[ruby] 스트링 치환 (replacement)  (0) 2015.12.09
ruby 공부 - interval단위로 DateTIme 시간 출력하기  (0) 2015.05.06
ruby - gil  (0) 2015.04.13
[ruby 공부 싸이트] rubymonk  (0) 2015.04.03
Posted by '김용환'
,



ruby 공부를 위해서 작성한 코드(snippet)이다.


ruby date, time을 이해하고, ruby optparse 공부한다. 

모듈을 만들어보고 테스트해보았다. 


https://gist.github.com/knight1128/c4c75d27e91779e26b5d


require 'date'

require 'time'

require 'optparse'


options = {:start_time => nil, :end_time => nil, :interval => nil}


parser = OptionParser.new do|opts|

opts.banner = "Usage: print-time-interval.rb --time [MIN | HOUR | DAY] --interval [5MIN | HOUR | DAY]"

opts.on('-s', '--start_time time', 'time') do |time|

options[:start_time] = time;

end


        opts.on('-e', '--end_time time', 'time') do |time|

                options[:end_time] = time;

        end


opts.on('-i', '--interval interval', 'interval') do |it|

options[:interval] = it.downcase;

end


opts.on('-h', '--help', 'Displays Help') do

puts opts

exit

end

end


parser.parse!


MIN = 60

HOUR = 60 * MIN

DAY = 24 * HOUR


INTERVAL_5MIN = 5 * MIN

INTERVAL_HOUR = 1 * HOUR

INTERVAL_DAY = 1 * DAY

INTERVAL_DEFAULT = INTERVAL_DAY


if options[:start_time] == nil

    options[:start_time] = '2014-12-30'

end


if options[:end_time] == nil

    options[:end_time] = '2015-1-1 1:0:0'

end


if options[:interval] == nil

interval = INTERVAL_DEFAULT

end


interval_array = ["day", "hour", "5min"]

interval_array.each do |it|

if (it == options[:interval])

if (it == "day")

interval = INTERVAL_DAY

elsif (it == "hour")

interval = INTERVAL_HOUR

elsif (it == "5min")

interval = INTERVAL_5MIN

end

end

end


if interval == nil

interval = INTERVAL_DEFAULT

end


time_start = Time.parse(options[:start_time])

time_end = Time.parse(options[:end_time])


module TimeStep

def step(end_time, incr)

t = self

while t <= end_time

yield t

t += incr

end

end

end



time_start.extend(TimeStep).step(time_end, interval) do |tick|

puts tick.strftime("%Y%m%d%H%M") #

end


Posted by '김용환'
,

ruby - gil

Ruby 2015. 4. 13. 21:27



ruby 공부를 하면서, Global Interpreter Lock(http://en.wikipedia.org/wiki/Global_Interpreter_Lock)에 대해서 알게 되었다. ruby 에서는 muli-thread 코딩이 할 수 있지만, 사실상 GIL 때문에 성능이 올라가지 않는다. 




https://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/





따라서 JVM을 업은 JRuby만 멀티 쓰레드를 잘 동작할 수 있다. 아니면, Mutl-process 방식을 써서 해야 한다.


반면, python쪽도 같이 GIL 이슈가 있다. Cpython은 GIL 이슈가 있고, pypy, Jython은 이슈가 없다. 



그림으로 GIL을 이해할 수 있는 블로그도 있다.

http://www.jstorimer.com/blogs/workingwithcode/8085491-nobody-understands-the-gil




Posted by '김용환'
,



https://rubymonk.com/

Posted by '김용환'
,