2016-04-18 5 views
-3

設定された文字数が設定値と等しい場合に文字列を返す方法を知りたいと思います。整数は、これら2つの数字で始まる場合、これは整数の最初の2文字が34の場合に文字列を返します

私は、文字列見てきたが、私はそれが私が理解できるものから

+5

試したことと動作しない方法を示します。 –

答えて

1

を動作させるように見えることはできません、あなたはこのような何かをしたい置く:

puts "Please enter your number:" 
number = gets.chomp 

result = number.to_s.start_with?("34") ? "Starts with 34" : "Doesn't start with 34" 

puts result 

そのコード(例:test.rb)でファイルを作成し、コマンドラインでruby tet.rbを実行します。

Please enter your number: 
3456 
Starts with 34 
+1

そこに '.to_s'の必要はありません、btw。 –

+0

Yeap、私の生産コードで '.to_s'をするのに慣れていました:)しかし、あなたは正しいです、ここでそれをする必要はありませんでした(+1)。 – Uzbekjon

0

これらの作業あなたは番号を検索したい文字列を整数の配列を持っている、またはあなたが入力するユーザーが必要な場合は数そのもの、またはあなただけのより多くの文字列を検索する場合のいずれかの場合その中の数字。それはあなたが本当に欲しいものに依存します!

arr = %w{4758 4759 123 097 384764} # an array of numbers 

p arr.find{|x| x.start_with?('38')} # '38' can be replaced with number of your choosing 
#=> '384764' 

#OR 

input = gets.chomp #user input 

p input if input.start_with?('38') # '38' can be replaced with number of your choosing 

#OR you can use regex to find a matching number in the input 

str = "Here's one number 95875 and another 65786" 

p str.scan(/95\d*/) # 95 are the first two digits of the number you're looking for 
#=> ["95875"] 
関連する問題