arrays - Ruby Turn string into integer -


i'm trying turn strings in array

values = (1..10).to_a + ["jack(11)", "queen(12)", "king(13)", "ace(14)"]

into integer, sort array

def straight(hand)    numbers = hand.each { |card| card.to_i }    numbers.sort  end

and keep getting error

["jack(11)", 9, 10, "queen(12)", "ace(14)"]  5carddraw.rb:58:in `sort': comparison of string 10 failed (argumenterror)

can tell me how can make work?

there couple misunderstandings here.

each

each iterates through array, passing each element block, , returns array itself. each not make changes array (unless tell to). since block calls to_i, end result numbers == hand:

ary = ["jack(11)", "queen(12)", "king(13)", "ace(14)"] tmp = ary.each { |card| card.to_i } p tmp # ["jack(11)", "queen(12)", "king(13)", "ace(14)"] 

so end sorting array containing numbers , strings, error complaining about. want use map, returns new array using results of block.

to_i

to_i simple conversion string integer: if string starts digits (ignoring whitespace), makes number out of digits. if string doesn't start digits, returns 0:

" 1 2".to_i       # 1 "99bottles".to_i  # 99 "match3".to_i     # 0 

since numbers in middle of strings, need more advanced, regexp, extract them:

"jack(11)"[/\d+/].to_i # 11 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -