SteenJobs
SteenJobs

Reputation: 45

Ruby - converting a string to a hash key

For example, I have the string "The Dark Knight 10.0" and I need to convert it into a key value hash of the form:

The Dark Knight => 10.0

How can I create a block to convert all strings of this form that I fetch from a .db file into a key value hash of the above form?

thanks for the help!

Upvotes: 0

Views: 1699

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

If you read a file into an array, each element in the array being a line from the file, you will have something like:

arr = ["The Dark Knight 10.0", "The White Knight 9.4", "The Green Knight 8.1"]

There are many ways to divide each string into two parts, for the key and value in a hash. This is one way:

arr.each_with_object({}) do |str,h|
  key, value = str.split(/\s(?=\d)/)
  h[key] = value
end
  #=> {"The Dark Knight"=>"10.0",
  #    "The White Knight"=>"9.4",
  #    "The Green Knight"=>"8.1"}

Here (?=\d) in the regex is called a "positive lookahead".

Upvotes: 0

daremkd
daremkd

Reputation: 8424

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}

Upvotes: 1

Manuel Franco
Manuel Franco

Reputation: 56

Assuming you already have the strings in a collection, iterate over them (1), split by the last space (2), and put the result into a hash using the two parts as key/value.

(1) See the 'each' method

(2) See the 'rpartition' method (example here : https://stackoverflow.com/a/20281590/1583220)

Hope it helps.

Upvotes: 0

Related Questions