YAML 사용하기

Reference

YAML은 XML에 비해 눈으로 데이터 확인이 용이하며, 해당 데이터를 쉽게 직렬화할 수 있다.

다음은 YAML의 hello program이다.

-
  name: Tom
  age: 32
-
  name: Dick
  age: 19  
EOS

config = YAML.load(yaml_string)    # from yaml_string

puts config[0]['age']  # 32
puts config[1]['name'] # Dick

YAML을 구성하기 위해서는 Array 로 할것인가, Hash로 할것인가로 결정해주면 된다. 물론 중첩도 가능하다.

arry = <<EOS
- [Tom, 32] # Array
- [Dick, 19] # Array
EOS

hash = <<EOS
{ name: Tom, age:32 } # Hash
EOS

다음은 기본적인 사용법을 정리한 hello_yaml.rb 이다.

# 필요한 파일
require 'yaml'

# 변환
str = "Hello, Yaml!"
puts str.to_yaml # y(str)


arr = ["one", "two", "three"]
puts arr.to_yaml # y(arr)

# 파일 저장
fileName = File.open('counting.yml', 'w')
    YAML.dump(arr, fileName)
fileName.close

# 파일 읽기
fileName = File.open('counting.yml', "r")
    newArr = YAML.load(fileName) # to array
fileName.close

puts newArr.to_yaml # y(newArr)

'Ruby' 카테고리의 다른 글

Koan - Methods  (0) 2014.03.01
Koan - Regular Expressions  (0) 2014.02.28
Koans - Symbols  (0) 2014.02.27
Ruby에서의 TDD  (0) 2014.02.22
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

Koan - Methods

Case 115

첫번째 테스트는 메소드의 리턴값의 class이다.

  def test_calling_with_variable_arguments
    assert_equal __, method_with_var_args.class
    assert_equal __, method_with_var_args
    assert_equal __, method_with_var_args(:one)
    assert_equal __, method_with_var_args(:one, :two)
  end

'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Regular Expressions  (0) 2014.02.28
Koans - Symbols  (0) 2014.02.27
Ruby에서의 TDD  (0) 2014.02.22
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

Koan - Regular Expressions

Case 83

정규표현식의 클래스는 Regexp이다.

def test_a_pattern_is_a_regular_expression
    assert_equal __, /pattern/.class
end
Case 84

/x?/는 존재하거나 존재하지 않는다는 의미이다. 테스트케이스의 의미처럼 option이라고 생각하자. 그리고 정규표현식의 기호는 다음을 참고하자. (http://www.nextree.co.kr/wp-content/uploads/2014/01/jhkim-140117-RegularExpression-06.png)

def test_question_mark_means_optional
    assert_equal __, "abbcccddddeeeee"[/ab?/]
    assert_equal __, "abbcccddddeeeee"[/az?/]
end
Case 88

/x*/는 x가 0번이상 반복하는 것을 의미한다. 3번째 테스트케이스는 nil이 아니다. (0번이상에 주의하자)

def test_asterisk_means_zero_or_more
    assert_equal __, "abbcccddddeeeee"[/ab*/]
    assert_equal __, "abbcccddddeeeee"[/az*/]
    assert_equal __, "abbcccddddeeeee"[/z*/]

    # THINK ABOUT IT:
    #
    # When would * fail to match?
end

# THINK ABOUT IT:
#
# We say that the repetition operators above are "greedy."
#
# Why?
Case 90

ruby에서 문자열[ ]는 문자열에서 정규표현식을 조사하는 구문이고, select는 조건을 만족하는 원소를 추출하는 메소드이다.

  def test_character_classes_give_options_for_a_character
    animals = ["cat", "bat", "rat", "zat"]
    assert_equal __, animals.select { |a| a[/[cbr]at/] }
  end
Case 93

공백문자 처리시에 \t\n도 포함된다.

  def test_slash_s_is_a_shortcut_for_a_whitespace_character_class
    assert_equal __, "space: \t\n"[/\s+/]
  end
Case 96

[/[^0-9]+/]는 not 으로 사용되었다.

  def test_a_character_class_can_be_negated
    assert_equal "the number is ", "the number is 42"[/[^0-9]+/]
  end
Case 97
  def test_shortcut_character_classes_are_negated_with_capitals
    assert_equal __, "the number is 42"[/\D+/]
    assert_equal __, "space: \t\n"[/\S+/]
    # ... a programmer would most likely do
    assert_equal __, "variable_1 = 42"[/[^a-zA-Z0-9_]+/]
    assert_equal __, "variable_1 = 42"[/\W+/]
  end
Case 98
  def test_slash_a_anchors_to_the_start_of_the_string
    assert_equal __, "start end"[/\Astart/]
    assert_equal __, "start end"[/\Aend/]
  end

'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Methods  (0) 2014.03.01
Koans - Symbols  (0) 2014.02.27
Ruby에서의 TDD  (0) 2014.02.22
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

Koans - Symbols

case 72

심볼은 C언어에서의 상수처럼 생각하면 될것 같다. 아래 두번째 test에서 두 객체의 object_id는 동일하다.

  def test_identical_symbols_are_a_single_internal_object
    symbol1 = :a_symbol
    symbol2 = :a_symbol

    assert_equal true, symbol1           == symbol2
    assert_equal false, symbol1.object_id == symbol2.object_id
  end
case 73

Symbol.all_symbols로 모든 심볼을 확인할수 있다. 화면 가득 채운 심볼들로 놀라게 될것이다. Ruby 내부적으로는 모든 참조되는 것들은 심볼로 관리하는 것이 아닌가 생각된다. 이 test는 함수 이름도 심볼로 등록된다는 것을 보여준다.

def test_method_names_become_symbols
    symbols_as_strings = Symbol.all_symbols.map { |x| x.to_s }
    assert_equal __, symbols_as_strings.include?("test_method_names_become_symbols")
end

# THINK ABOUT IT:
#
# Why do we convert the list of symbols to strings and then compare
# against the string value rather than against symbols?
case 74

"What is the sound of one hand clapping?"는 심볼로 저장되지 않고, constant 이름이 심볼로 저장된다.

in_ruby_version("mri") do
    RubyConstant = "What is the sound of one hand clapping?"
        def test_constants_become_symbols
        all_symbols_as_strings = Symbol.all_symbols.map { |x| x.to_s }

        assert_equal __, all_symbols_as_strings.include?(__)
    end
 end
case 75

문자열은 심볼로 저장되지 않으나, 변환 가능하다.

def test_symbols_can_be_made_from_strings
    string = "catsAndDogs"
    assert_equal __, string.to_sym
end
case 78

심볼은 interpolation 이 가능하다.

  def test_to_s_is_called_on_interpolated_symbols
    symbol = :cats
    string = "It is raining #{symbol} and dogs."

    assert_equal __, string
  end

'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Methods  (0) 2014.03.01
Koan - Regular Expressions  (0) 2014.02.28
Ruby에서의 TDD  (0) 2014.02.22
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

요즘에 TDD에 좀 더 관심을 가지고, 스터디할만한 내용을 찾고 있었다.

TDD tutorial 을 찾아보면, 간략히 클래스에 함수 한 두개 추가하여 assert 정도 체크하는 예제만 있는데, 실제 프로젝트에서 쓸 만한 tutorial 가 있으면 좋겠다 했다.

Google에서 검색하던 중에 다음을 발견하였다. ( http://stackoverflow.com/questions/4919442/how-to-learn-tdd-with-ruby/4919476#4919476?s=71d4f74daaf64e7685e7266c21dfe34f )


How to learn TDD with Ruby?

Try RubyKoans.

share|improve this answer
 
RubyKoans are great because they teach ruby based on tests. Definitely a good way to learn TDD by example. Also recommended: Ruby Best Practices –  Mobbit Feb 7 '11 at 9:22

 

RubyKoans을 download해서 해 보는데, ruby study도 되고 내가 원했던 TDD 예제로도 적당해서 만족스럽다.

'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Methods  (0) 2014.03.01
Koan - Regular Expressions  (0) 2014.02.28
Koans - Symbols  (0) 2014.02.27
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

Singing with Sinatra 예제를 따라하는 중이다.

원래는 Ruby code를 변경할때마다 웹서버를 중단시키고 재실행해주어야 하는데,

shotgun을 이용하면 이런 과정 없이 브라우저에서 바로 수정 내용을 확인할 수 있다.


문제는 Mac에서는 shotgun이 잘 동작하는데,

Windows에서는 다음의 에러를 출력한다.

C:/Ruby193/lib/ruby/gems/1.9.1/gems/shotgun-0.9/bin/shotgun:99:in ``': No such file or directory - uname (Errno::ENOENT)

        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/shotgun-0.9/bin/shotgun:99:in `block in <top (required)>'

        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/shotgun-0.9/bin/shotgun:98:in `each'

        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/shotgun-0.9/bin/shotgun:98:in `find'

        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/shotgun-0.9/bin/shotgun:98:in `<top (required)>'

        from C:/Ruby193/bin/shotgun:23:in `load'

        from C:/Ruby193/bin/shotgun:23:in `<main>'


shotgun의 이러한 문제는 Sinatra::Contribute project에 포함되어 있는 Reloader로서 해결할 수 있었다.

다음과 같이 설치하고

gem install sinatra-contrib


다음처럼 사용하면 된다.

require "sinatra"
require "sinatra/reloader" if development?

# Your classic application code goes here...


'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Methods  (0) 2014.03.01
Koan - Regular Expressions  (0) 2014.02.28
Koans - Symbols  (0) 2014.02.27
Ruby에서의 TDD  (0) 2014.02.22

+ Recent posts