2014-07-06 2 views
0

짧은 팁의 주요 포인트는 사용자의 입력에서 7 자리 숫자 (백만 이상)로 구성된 가격을 찾는 것이 었습니다. 루비 클래스 메소드 범위. 왜 방법은 사적인가?

class Price 
    attr_accessor :data 

    def initialize(str) 
    @data = str 
    end 

    def lookup 
    @data.select do |i| 
     i[/\d{1,7}+/] 
    end 
    end 

    def print_and_max 
    puts "Here comes the maximum" 
    # some code and voila 
    end 

end 

prices = gets.to_a 
str = Price.new(prices) 
print str.lookup 

내가이 오류를 얻을 :

내가이 쓴

price.rb:21:in `<main>': undefined method `to_a' for "124789358124 12478912578915 50000000 50204500\n":String (NoMethodError) 

확인을, 다시 해보자 : 결과 다음

class Price 
    attr_accessor :data 

    prices = [] 

    def initialize(str) 
    @data = str 
    end 

    def lookup 
    @data.select do |i| 
     i[/\d{1,7}+/] 
    end 
    end 

    def print_and_max 
    puts "Here comes the maximum" 
    # some code and voila 
    end 

end 

prices = gets 
str = Price.new(prices) 
print str.lookup 

을 그리고 것은 그와 같다 :

price.rb:11:in `lookup': private method `select' called for "124789358124 12478912578915 50000000 50204500":String (NoMethodError) 

Ruby에서 메서드 범위를 완전히 이해하지 못하는 것 같습니다. 주요 아이디어는 공백이나 다른 것으로 구분 된 문자열을 집 어서 배열로 변환하여 인쇄하는 것입니다. 최대 값을 출력하는 작성 메소드는 선택 사항입니다. 왜 select 메소드가 비공개인가? 나는 Price 클래스를 자식으로 Array에 연결하려고 시도했지만 select 메서드는 private로 유지되었습니다.

irb(main):028:0* str.data 
=> [125215213] 

.lookup가되지 않습니다 : : 내가 잘못 뭐하는 거지

irb(main):029:0> str.lookup 
TypeError: no implicit conversion of Regexp into Integer 
    from (irb):11:in `[]' 
    from (irb):11:in `block in lookup' 
    from (irb):10:in `select' 
    from (irb):10:in `lookup' 
    from (irb):29 
    from /Users/shu/.rbenv/versions/2.0.0-p481/bin/irb:12:in `<main>' 
irb(main):030:0> 

prices = [125215213] 

@data에 액세스 :

나는이 시도했습니다? 발견 한 ""모든 그것을 분리,

price = gets.chomp.split(" ") 

문자열을 배열로 분할합니다 : 이것에

price = gets 

:

+2

주된 문제는 String을 Array처럼 취급하려고한다는 것입니다. –

+0

오류 메시지를 올바르게 해석하는 것이 도움이 필요한 것 같습니다. 당신의 추측은 그다지 뚜렷하지 않습니다. –

답변

0

는 사용자 입력은 다음과 같습니다 경우

prices = gets.split 

분할이 덩어리를 분할하는 String 클래스 방법 : "124789358124 12478912578915 50000000 50204500"

그런 다음이 같은 배열로 그를 설정할 수 있습니다 텍스트를 배열 요소에 저장합니다. 기본적으로 공백으로 나뉘지만 공백으로 나눠서 사용하지 않는 경우에는 인자로 전달할 수 있습니다 (실제와 같이).

0

는이 라인을 변경해야합니다. 그리고 chomp는 사용자가 입력 한 후에 추가 될 개행을 제거합니다.