Home > Net >  How to convert ruby array to support PostgreSQL array in ruby
How to convert ruby array to support PostgreSQL array in ruby

Time:01-03

I have a following ruby array, need to convert array to support PostgresSQL array.

The array I have

ruby_array = ["9771", "9773", "9778", "9800", "9806"] 

I need to convert this to following format

postgresSQL_array = {"9771", "9773", "9778", "9800", "9806"} 

by using ruby

CodePudding user response:

If you simply need to create a string in that format, you can stringify the Ruby array, removing the first and last characters and inserting it between curly braces.

irb(main):001:0> ruby_array = ["9771", "9773", "9778", "9800", "9806"] 
=> ["9771", "9773", "9778", "9800", "9806"]
irb(main):002:0> postgresSQL_array = "{#{ruby_array.to_s[1...-1]}}"
=> "{\"9771\", \"9773\", \"9778\", \"9800\", \"9806\"}"
irb(main):003:0> puts postgresSQL_array
{"9771", "9773", "9778", "9800", "9806"}
=> nil

CodePudding user response:

If you're using the PG gem, use PG::TextEncoder::Array to convert a Ruby Array to a PostgreSQL Array.

connection.exec(
  "select $1::int[]",
  [PG::TextEncoder::Array.new.encode([1, 2, 3])]
)

If you're using Ruby on Rails, simply pass the Array as a parameter and it will convert for you.

Model.where(nums: [1,2,3])

Note that most things you can do with PostgreSQL Arrays are better done with JSONB.

  • Related