How to add to an existing hash in Ruby

前端 未结 7 1750
悲哀的现实
悲哀的现实 2021-01-30 00:02

In regards to adding an key => value pair to an existing populated hash in Ruby, I\'m in the process of working through Apress\' Beginning Ruby and have just fi

7条回答
  •  轮回少年
    2021-01-30 00:42

    hash {}
    hash[:a] = 'a'
    hash[:b] = 'b'
    hash = {:a => 'a' , :b = > b}
    

    You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
    For example:

    movies ={}
    movie = gets.chomp
    rating = gets.chomp
    movies[movie.to_sym] = rating.to_int
    # movie will convert to a symbol as a key in our hash, and 
    # rating will be an integer as a value.
    

提交回复
热议问题