You need a regular expression to isolate the name of the movie and the rating (if 10.0 is a rating). I'll need more input in order to provide a more accurate regular expression, but for the one above, this does the job (it also takes care if the movie, is say, Transformers 2 9.0, it will correctly take Transformers 2 => 9.0):
def convert_string_into_key_value_and_add_to_hash(string, hash_to_add_to)
name = string[/^[\w .]+(?=\s+\d+\.\d+$)/]
number = string[/\d+\.\d+$/].to_f
hash_to_add_to[name] = number
end
str = "The Dark Knight 10.0"
hash = {}
convert_string_into_key_value_and_add_to_hash(str, hash)
p hash #=> {"The Dark Knight"=>10.0}
The more 'Rubyist' way is to use rpartition:
def convert_string_into_key_value_and_add_to_hash(string, hash_to_add_to)
p partition = string.rpartition(' ')
hash_to_add_to[partition.first] = partition.last.to_f
end
str = "The Dark Knight 2 10.0"
hash = {}
convert_string_into_key_value_and_add_to_hash(str, hash)
p hash #=> {"The Dark Knight 2"=>10.0}