skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search