rubyamazon-web-servicesamazon-dynamodbaws-sdk-ruby

DynamoDB returning Numbers as decimals not integers in Ruby


I’m storing a few numbers in a Map. They’re being set correctly, and appear in DynamoDB interface correctly:

results List [1]
    0 Map
        dateTimeCompleted Number : 1554138543
        questionsAnswered Number : 10
        questionsCorrect Number : 5

However, when I get the response, using the AWS Ruby SDK, they’ve turned into decmimals.

"dateTimeCompleted"=>0.1554376141e10,
"questionsAnswered"=>0.2e2,
"questionsCorrect"=>0.5e1

Note this aren’t from the same item, so I’m aware the numbers don’t match, the format is the concern.

How do I tell the SDK that I’d like them as integers?

or

Do I need to map them in Ruby to integers myself?


Solution

  • Use to_i:

    0.1554376141e10.to_i # => 1554376141
    

    To convert all the values in a Hash:

    my_hash.reduce({}) { |memo, (k,v)| memo[k] = v.to_i; memo }
    

    or:

    my_hash.transform_values(&:to_i)