http://www.tutorialspoint.com/ruby/ruby_if_else.htm


ruby 의 if 문은 , 앞 if / 뒤 if / unless / case 로 나눠진다.


ruby를 쓰지 않는 나같은 ruby 초보자로서는 다음 실수를 할 수 있다.

if 문 뒤에 바로 실행문을 쓸 수 없다. 



a = 1

if (a ==1) puts "true"

end


위의 경우는 아래와 같이 써야 한다.



a = 1

if (a ==1) then puts "true"

end





a = 1

if (a ==1) # 다음 줄로 쓰기

   puts "true"

end




'Ruby' 카테고리의 다른 글

ruby - gil  (0) 2015.04.13
[ruby 공부 싸이트] rubymonk  (0) 2015.04.03
[ruby] irb에서 clear, load file, ls, cd, pwd 하기  (0) 2014.09.14
[ruby] irb 안에서 irb 사용하기  (0) 2014.09.14
[ruby] irb 빠른 종료 (부제 : alias)  (0) 2014.09.14
Posted by '김용환'
,

irbrc에 넣을 만한 좋은 기능 중 인터넷에서 본 것 중, 나한테 쓸만한 것만 모았다. 

화면 깨끗이(clear), 현재 파일 또는 다른 파일 열기, ls/cd/pwd 하기 정도..


$ cat >> ~/.irbrc


# screen clear

def clear

  system 'clear'

end

alias c clear



# Load / reload files faster

# http://www.themomorohoax.com/2009/03/27/irb-tip-load-files-faster

def fl(file_name)

   file_name += '.rb' unless file_name =~ /\.rb/

   @@recent = file_name 

   load "#{file_name}"

end

 

def rl

  fl(@@recent)

end



# from http://themomorohoax.com/2009/03/27/irb-tip-load-files-faster

def ls

  %x{ls}.split("\n")

end

 

def cd(dir)

  Dir.chdir(dir)

  Dir.pwd

end

 

def pwd

  Dir.pwd

end



Posted by '김용환'
,


irb안에서 irb 사용이 가능하다.  즉 새로운 session을 만들 수 있고 종료할 수 있다. 

session 이동(session switching)은 fg #숫자 로 이동한다. 




my_string = "foo"

=> "foo"

>> foo = "foo"

=> "foo"

>> irb

>> foo

NameError: undefined local variable or method `foo' for main:Object

from (irb#1):1

>> jobs

=> #0->irb on main (#<Thread:0x007fd71b05b7d0>: stop)

#1->irb#1 on main (#<Thread:0x007fd71b1beeb0>: running)

>> fg 0

=> #<IRB::Irb: @context=#<IRB::Context:0x007fd71b0b57a8>, @signal_status=:IN_EVAL, @scanner=#<RubyLex:0x007fd71b0a8710>>

>> foo

=> "foo"

>> jobs

=> #0->irb on main (#<Thread:0x007fd71b05b7d0>: running)

#1->irb#1 on main (#<Thread:0x007fd71b1beeb0>: stop)

>> irb

>> jobs

=> #0->irb on main (#<Thread:0x007fd71b05b7d0>: stop)

#1->irb#1 on main (#<Thread:0x007fd71b1beeb0>: stop)

>> kill 1

=> [1]

>> jobs

=> #0->irb on main (#<Thread:0x007fd71b05b7d0>: stop)

#2->irb#2 on main (#<Thread:0x007fd71b0f9048>: running)

Posted by '김용환'
,



ruby의 irb에서 종료를 하려면 'exit() 엔터' 해야 쉘로 나올 수 있다. ctrl+c도 안되서.. 확인했더니 alias가 있다.



$ cat >> .irbrc

alias q exit; alias quit exit; alias e exit

Samuel ~ $ irb

>> e

Samuel ~ $ irb

>> quit

Samuel ~ $ irb

>> q



Posted by '김용환'
,


ruby irb 를 풍요롭게 쓰기 위해서 tab 을 누르면 자동완성(irb/completion)해주고, 디버그 색상(wirble)도 예쁘게 해줄 수 있다.  wirble은 https://github.com/blackwinter-attic/wirble 에서 설명이 되어 있다. 




$ gem install wirble



$ cat ~/.irbrc 

require 'irb/completion'

require 'wirble'


# start wirble (with color)

Wirble.init

Wirble.colorize



irb를 실행하고. gem으로 다운로드한 zk를 사용해 본다. ZK.n 을 입력 후 tab을 사용하면 후보 메소드들이 출력된다. 


$ irb

>> require 'zk'

=> true

>> ZK.n

ZK.name      ZK.new       ZK.new_pool  ZK.nil?

Posted by '김용환'
,

hbase에서 zookeeper의 znode 생성시 path의 의 단계가 많을 수록 고달파진다.  


atomic operation이라 'mkdir -p 디렉토리명'처럼 한번에 node 설정이 안되어서 일일히 아래와 같이 넣어야 하는데.. 이 방식은 jvm이 총 5번 뜨고 매번 connection을 맺는 구조라 그리 좋지 않다. 


  ${HBASE_HOME}/bin/hbase zkcli create '/apache' null >> "${ZK_LOG_FILE}" 2>&1
  ${HBASE_HOME}/bin/hbase zkcli create '/apache/phase' null >> "${ZK_LOG_FILE}" 2>&1
  ${HBASE_HOME}/bin/hbase zkcli create '/apache/phase/local' null >> "${ZK_LOG_FILE}" 2>&1
  ${HBASE_HOME}/bin/hbase zkcli create '/apache/phase/local/config' null >> "${ZK_LOG_FILE}" 2>&1
  ${HBASE_HOME}/bin/hbase zkcli create '/apache/phase/local/config/zoo' 'true' >> "${ZK_LOG_FILE}" 2>&1


이럴 때에는 ruby의 'zk'모듈(https://github.com/zk-ruby/zk)을 사용하면 된다.

자세한 예제는 아래에 있다. 예제는 single thread와 event queue 방식이 있다. 

https://github.com/zk-ruby/zk/wiki



간단히 사용할 것이라  다음과 같이 적용했다.  


zk.rb

# encoding: utf-8
require 'zk'

zk = ZK.new('localhost:2181')

zk.register('/apache/phase/local/config/zoo') {}
begin
  zk.create('/apache', '')
rescue ZK::Exceptions::NodeExists => msg
  puts msg
end

begin
  zk.create('/apache/phase', '')
rescue ZK::Exceptions::NodeExists =>msg
  puts msg
end

...


zk.close!



Posted by '김용환'
,

[ruby] expect

Ruby 2014. 8. 29. 12:02


ruby에서 마땅한 expect 가 없었던 것 같다. (ruby 지인은 bin/expect를 활용하는 방식을 주로 사용했다고 한다.) 함 찾아보고 안되면 bin/expect 쓰려했는데, 적당히 쓸만한 오픈소스를 발견했다.


https://github.com/abates/ruby_expect  의 expect를 써봤는데, 쓸만하다. ruby expect 를 원하는 분들에게 희소식일듯 하다.



 

나는 최신 버전을 사용하고 간단하게 require_relative를 쓰는 것을 좋아해서https://github.com/abates/ruby_expect 의 ruby 소스 두개를 하나로 merge해서 ruby 하나 파일로 만들었다. https://github.com/knight1128/ruby-expect




사용법



$ wget https://raw.githubusercontent.com/knight1128/ruby-expect/master/expect.rb

$ vi test.rb






require_relative 'expect'


DB_USER_NAME  = "www"

DB_USER_PWD   = "wwwteam"




mysql_version = `mysql --version | tr [,] ' ' | tr [:space:] '\n' | grep -E '([0-9]{1,3}[\.]){2}[0-9]{1,3}'`



if mysql_version > "5.6.0"

  SUPPORT_MYSQL_5DOT6 = true

else

  SUPPORT_MYSQL_5DOT6 = false

end



if SUPPORT_MYSQL_5DOT6

  exp = RubyExpect::Expect.spawn("mysql_config_editor set --login-path=localhost --host=localhost --user=#{DB_USER_NAME} --password")

  exp.procedure do

    each do

        expect /Enter password:/ do

          send DB_USER_PWD

        end

    end

  end

end



Posted by '김용환'
,


ruby 언어를 새로 배우면서 많이 혼란스럽다. 공부하면서 계속 정리 해야 할 것 같다. 

(계속 내용 변경 예정)



reserved word
http://www.tutorialspoint.com/ruby/ruby_quick_guide.htm

equal check
http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and

4 variables and scope
http://strugglingwithruby.blogspot.dk/2010/03/variables.html

operator
http://www.tutorialspoint.com/ruby/ruby_operators.htm

loop
http://www.tutorialspoint.com/ruby/ruby_loops.htm

class & module
http://stackoverflow.com/questions/151505/difference-between-a-class-and-a-module
http://www.rootr.net/rubyfaq-8.html

symbol
http://www.rootr.net/rubyfaq-6.html


java 개발에서 ruby 개발할 때 주의 사항
https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/
(==, equal이 java와 ruby는 반대다...)


일반 operator 설명 
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

ruby 파일을 읽는 4가지 방법

https://practicingruby.com/articles/ways-to-load-code

block, proc, lamba 비교
http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/


inspect & to_s

http://stackoverflow.com/questions/2625667/why-do-this-ruby-object-have-two-to-s-and-inspect-methods-that-seems-do-the-same


yield

http://stackoverflow.com/questions/10451060/use-of-yield-and-return-in-ruby

http://stackoverflow.com/questions/764134/rubys-yield-feature-in-relation-to-computer-science/765126#765126



! (bang)

http://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods

https://coderwall.com/p/rgvk4g

irb(main):015:0* name = 'knight76'

=> "knight76"

irb(main):016:0> name.sub('k', 'x')

=> "xnight76"

irb(main):017:0> name

=> "knight76"

irb(main):018:0> name.sub!('k', 'x')

=> "xnight76"

irb(main):019:0> name

=> "xnight76"

http://stackoverflow.com/questions/7561572/why-would-you-use-a-operator


named parameter

http://brainspec.com/blog/2012/10/08/keyword-arguments-ruby-2-0/


lazy init

http://patshaughnessy.net/2013/4/3/ruby-2-0-works-hard-so-you-can-be-lazy


동적 클래스 메소드 재정의 (monkeypatching / open class)

http://www.runtime-era.com/2012/12/reopen-and-modify-ruby-classes-monkey.html


array.sample(랜덤으로 값 가지고 오기)

http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-sample



* 테스트쪽


rspec-expect
https://www.relishapp.com/rspec/rspec-expectations/v/3-0/docs/built-in-matchers/equality-matchers

rspec 

http://code.tutsplus.com/tutorials/ruby-for-newbies-testing-with-rspec--net-21297

http://magazine.rubyist.net/?0035-RSpecInPractice

http://magazine.rubyist.net/?0021-Rspec

http://magazine.rubyist.net/?0032-TranslationArticle

http://blog.carbonfive.com/2010/10/21/rspec-best-practices/

(한글) http://betterspecs.org/ko/index.html
(command line) https://www.relishapp.com/rspec/rspec-core/v/2-4/docs/command-line


binding.pry (irb와 비슷)
http://knight76.tistory.com/entry/ruby-%EB%94%94%EB%B2%84%EA%B7%B8debug-%EC%89%BD%EA%B2%8C-%ED%95%98%EA%B8%B0


sinatra (http url mockup)

http://www.sinatrarb.com/intro.html

get '/download/*.*' do |path, ext|
  [path, ext] # => ["path/to/file", "xml"]
end


faraday - http 연결 client

http://mislav.uniqpath.com/2011/07/faraday-advanced-http/


active record - DB 연결

http://rubylearning.com/satishtalim/ruby_activerecord_and_mysql.html



<특이 함수>

- list의 empty string을 없애기
url.reject! { |c| c.empty? }

- string에서 grep을 바로 쓸 수 없어서. enumerable로 변경해서 grep을 사용

link.lines.grep(/aaa/)



Posted by '김용환'
,

ruby 2.1.0를 사용중이며, debug(디버그)를 위해 pry와 pry-nav를 설치한다. 


$ gem install pry

$ gem install pry-nav




ruby 테스트 코드 작성

$ cat Point.rb

require 'pry'

class Point

  attr_accessor :x, :y

  attr_reader :zzz

  def say_hello

    puts "Hello World"

  end


end


def another_hello

  puts "Hello World (from a method)"

end


p = Point.new

p.say_hello

p.x = 10

binding.pry

puts p.x

another_hello



소스 중에 break하고 싶은 곳을 'binding.pry'을 입력하고 실행하면, 디버그콘솔화면이 나온다. 간단하게 테스를 할 수 있다. 


 $ ruby Point.rb

Hello World


From: /mydev/test/ruby/Point.rb @ line 18 :


    13: end

    14:

    15: p = Point.new

    16: p.say_hello

    17: p.x = 10

 => 18: binding.pry

    19: puts p.x

    20: p.zzz = 20

    21: another_hello


[1] pry(main)> puts p.x

10

=> nil

[2] pry(main)> puts p.y

=> nil

[5] pry(main)> def plus(a, b)

[5] pry(main)*   return a + b

[5] pry(main)* end

=> :plus

[6] pry(main)> p.y = 0

=> 0

[7] pry(main)> plus(p.x, p.y)

=> 10

[8] pry(main)> exit





디버그 에서 하듯이 setp/next/continue/exit를 할 수 있다. 



Samuel /mydev/test/ruby $ ruby Point.rb

Hello World


From: /mydev/test/ruby/Point.rb @ line 18 :


    13: end

    14:

    15: p = Point.new

    16: p.say_hello

    17: p.x = 10

 => 18: binding.pry

    19: puts p.x

    20: another_hello


[1] pry(main)> next


From: /mydev/test/ruby/Point.rb @ line 19 :


    14:

    15: p = Point.new

    16: p.say_hello

    17: p.x = 10

    18: binding.pry

 => 19: puts p.x

    20: another_hello





주로 사용하는 ruby 명령어는 다음과 같다. 



  • next : 다음 한 단계 진행
  • step : 다음 한 단계 진행 또는 메소드 진입
  • continue : 다음 binding.pry 까지 진행 또는 binding.pry 없으면 코드 끝까지 실행
  • quit, exit : 모든 코드 실행후 종료
  • !!! : 바로 종료
  • help : 도움말


기타 

  • watch 테스트 

[1] pry(main)> watch p

Watching p

watch: p => #<Point:0x007ffa1580fb80 @x=10>





Posted by '김용환'
,