문자열이 ten
인 경우이를 Ruby의 정수 10
으로 변환 할 수 있습니까? (아마도 레일에?)문자열 숫자 (워드 형식)를 정수형 루비로 변환
개발자는 tryruby.org에서 가치를 둡니다. 튜토리얼 here에서 "to_i는 정수를 정수로 변환합니다."라고 말하면서 왜 "to_i 문자열을 정수 (숫자)로 변환합니다. "
유형에서 정수로 변환 할 수있는 변수 유형은 무엇입니까?
문자열이 ten
인 경우이를 Ruby의 정수 10
으로 변환 할 수 있습니까? (아마도 레일에?)문자열 숫자 (워드 형식)를 정수형 루비로 변환
개발자는 tryruby.org에서 가치를 둡니다. 튜토리얼 here에서 "to_i는 정수를 정수로 변환합니다."라고 말하면서 왜 "to_i 문자열을 정수 (숫자)로 변환합니다. "
유형에서 정수로 변환 할 수있는 변수 유형은 무엇입니까?
확인 :
당신이 문자열 숫자에서 가고 싶은 경우
,이 출발점이다. 추가 정보에서 는 :require 'numbers_in_words'
require 'numbers_in_words/duck_punch'
112.in_words
#=> one hundred and twelve
"Seventy million, five-hundred and fifty six thousand point eight nine three".in_numbers
#=> 70556000.893
String#to_i
은 숫자 문자 만 선택하므로 원하는 방식으로 작동하지 않습니다. 레일스 메소드와 관련하여 약간의 차이가있을 수 있지만 그 동작은 원래 의도 인 String#to_i
과 충돌하기 때문에 반드시 메소드 이름 to_i
을 가지지 않을 것입니다.
to_i
을 갖는 것은 Strings
일뿐만 아니라, NilClass
, Time
, Float
, Rational
(그리고 아마도 다른 클래스들도 마찬가지입니다).
"3".to_i #=> 3
"".to_i #=> 0
nil.to_i #=> 0
Time.now.to_i #=> 1353932622
(3.0).to_i #=> 3
Rational(10/3).to_i #=> 3
이 그들의 숫자 상당 문자열의 간단한 검색은 다음과 같습니다
str_to_int_hash = {
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9,
'ten' => 10
}
str_to_int_hash['ten']
=> 10
그것은 많은 다른 누락 된 항목이 있습니다 분명하지만 아이디어를 보여줍니다. 숫자 변환에 단어를 처리하기위한 밖으로 this gem
int_to_str_hash = Hash[str_to_int_hash.map{ |k,v| [v,k] }]
int_to_str_hash[10]
=> "ten"
작은 값의 시작점이지만 임의로 큰 수로 확장하는 데 필요한 일반성을 암시하지 않습니다. – Michael
그래서 "간단한 조회"라고했습니다. OP는 단순한 숫자 이상을 언급하지 않기 때문에 매우 혼란스럽고 자주 묻지 않는 질문으로 충분합니다. 이 외에도 훨씬 더 철저한 코드가 필요합니다. –
나는 그것을했을 방법.
def n_to_s(int)
set1 = ["","one","two","three","four","five","six","seven",
"eight","nine","ten","eleven","twelve","thirteen",
"fourteen","fifteen","sixteen","seventeen","eighteen",
"nineteen"]
set2 = ["","","twenty","thirty","forty","fifty","sixty",
"seventy","eighty","ninety"]
thousands = (int/1000)
hundreds = ((int%1000)/100)
tens = ((int % 100)/10)
ones = int % 10
string = ""
string += set1[thousands] + " thousand " if thousands != 0 if thousands > 0
string += set1[hundreds] + " hundred" if hundreds != 0
string +=" and " if tens != 0 || ones != 0
string = string + set1[tens*10+ones] if tens < 2
string += set2[tens]
string = string + " " + set1[ones] if ones != 0
string << 'zero' if int == 0
p string
end
;
n_to_s(rand(9999))
OP는 '10 ~ 10, 9 ~ 9 등 '을 의미합니다. –
@slivu OP는 여러 질문을하고 있습니다. 나는 마지막 것만 응답하고있다. – sawa