All tutorials

Ruby

intermediate

The Ruby wrapper is useful for Ruby developers who wish to seamlessly integrate the what3words Public API into their Ruby applications, without the hassle of having to manage the low level API calls themselves.

A full example of how to integrate the what3words Ruby wrapper is available in our GitHub repository.

1Get API key
2Installation

The library is available through RubyGems.

You can simply add this line to your application’s Gemfile:

gem 'what3words', '~> 3.3'
Copied

And then execute:

bundle
Copied

Or install it yourself as:

gem install what3words
Copied
3Setup

If not using Bundler, require it:

require 'what3words'
Copied
4Initialise

The wrapper will point to the public version of the what3words API, to initialise it simply:

what3words = What3Words::API.new(:key => "YOURAPIKEY")
Copied
5Usage

Convert to what3words address

This function converts coordinates (expressed as latitude and longitude) to a what3words address.

More information about ConvertTo3wa, including returned results is available in the what3words REST API documentation.

Find the words for (29.567041, 106.587875):

what3words.convert_to_3wa [29.567041, 106.587875]

# Expected Output
# => {:country=>"CN", :square=>{:southwest=>{:lng=>106.58786, :lat=>29.567028}, :northeast=>{:lng=>106.587891, :lat=>29.567055}}, :nearestPlace=>"Chongqing", :coordinates=>{:lng=>106.587875, :lat=>29.567041}, :words=>"disclose.strain.redefined", :language=>"en", :map=>"https://w3w.co/disclose.strain.redefined"}
Copied

Convert to coordinates

This function converts a what3words address to a position, expressed as coordinates of latitude and longitude.

It takes the words parameter as a string of a what3words 'table.book.chair'

More information about ConvertToCoordinates, including returned results is available in the what3words REST API documentation.

Find the words for ///prom.cape.pump:

what3words.convert_to_coordinates "prom.cape.pump"

# Expected Output
# => {:country=>"GB", :square=>{:southwest=>{:lng=>-0.195426, :lat=>51.484449}, :northeast=>{:lng=>-0.195383, :lat=>51.484476}}, :nearestPlace=>"Kensington, London", :coordinates=>{:lng=>-0.195405, :lat=>51.484463}, :words=>"prom.cape.pump", :language=>"en", :map=>"https://w3w.co/prom.cape.pump"}
Copied

AutoSuggest

When presented with a what3words address which may be incorrectly entered, AutoSuggest returns a list of potential correct 3 word addresses. It needs the first two words plus at least the first character of the third word to produce suggestions.

This method provides corrections for mis-typed words (including plural VS singular), and words being in the wrong order.

Optionally, clipping can narrow down the possibilities, and limit results to:

  • One or more countries
  • A geographic area (a circle, box or polygon)

This dramatically improves results, so we recommend that you use clipping if possible.

To improve results even further, set the Focus to user’s current location. This will make AutoSuggest return results which are closer to the user.

More information about AutoSuggest, including returned results is available in the what3words REST API documentation.

Code example Simple basic call:

what3words.autosuggest 'trop.caler.perdre', language: 'fr'

# Expected Output
# => {:suggestions=>[{:country=>"FR", :nearestPlace=>"Saint-Lary-Soulan, Hautes-Pyrénées", :words=>"trier.caler.perdre", :rank=>1, :language=>"fr"}, {:country=>"ET", :nearestPlace=>"Asbe Teferi, Oromiya", :words=>"trôler.caler.perdre", :rank=>2, :language=>"fr"}, {:country=>"CN", :nearestPlace=>"Ulanhot, Inner Mongolia", :words=>"froc.caler.perdre", :rank=>3, :language=>"fr"}]}
Copied

Code example AutoSuggest, clipping the results returned to the United Kingdom and Belgium:

what3words.autosuggest 'disclose.strain.redefin', 'clip-to-country': 'GB,BE'

# Expected Output
# => {:suggestions=>[{:country=>"GB", :nearestPlace=>"Nether Stowey, Somerset", :words=>"disclose.retrain.redefined", :rank=>1, :language=>"en"}, {:country=>"BE", :nearestPlace=>"Zemst, Flanders", :words=>"disclose.strain.reckon", :rank=>2, :language=>"en"}, {:country=>"GB", :nearestPlace=>"Waddington, Lincolnshire", :words=>"discloses.trains.redefined", :rank=>3, :language=>"en"}]}
Copied

Code example AutoSuggest, Focus on (51.4243877,-0.34745).

what3words.autosuggest 'filled.count.soap', focus: [51.4243877,-0.34745]

# Expected Output
# => {:suggestions=>[{:country=>"GB", :nearestPlace=>"Bayswater, London", :words=>"filled.count.soap", :rank=>1, :distanceToFocusKm=>15, :language=>"en"}, {:country=>"GB", :nearestPlace=>"Orsett, Essex", :words=>"fills.count.slap", :rank=>2, :distanceToFocusKm=>48, :language=>"en"}, {:country=>"GB", :nearestPlace=>"Cobham, Surrey", :words=>"field.count.slap", :rank=>3, :distanceToFocusKm=>14, :language=>"en"}]}
Copied

Code example AutoSuggest, with Generic Voice input type.

what3words.autosuggest 'fun with code', 'input-type': 'generic-voice', language: 'en'

# Expected Output 
# => {:suggestions=>[{:country=>"US", :nearestPlace=>"Homer, Alaska", :words=>"fund.with.code", :rank=>1, :language=>"en"}, {:country=>"AU", :nearestPlace=>"Kumpupintil, Western Australia", :words=>"funk.with.code", :rank=>2, :language=>"en"}, {:country=>"US", :nearestPlace=>"Charleston, West Virginia", :words=>"fund.with.cove", :rank=>3, :language=>"en"}]}
Copied

Grid section

Grid section returns a section of the what3words 3m x 3m grid as a set of horizontal and vertical lines covering the requested area, which can then be drawn onto a map.

The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig error will be returned.

More information about GridSection, including returned results is available in the what3words REST API documentation.

Get a grid for 52.207988,0.116126) in the south west, and 52.208867,0.117540 in the north east:

what3words.grid_section '52.208867,0.117540,52.207988,0.116126'

# Expected Output
# => {:lines=>[{:start=>{:lng=>0.116126, :lat=>52.20801}, :end=>{:lng=>0.11754, :lat=>52.20801}}, {:start=>{:lng=>0.116126, :lat=>52.208037}, :end=>{:lng=>0.11754, :lat=>52.208037}}, {:start=>{:lng=>0.116126, :lat=>52.208064}, :end=>{:lng=>0.11754, :lat=>52.208064}}, ___...___ ]}
Copied

Available languages

This function returns the currently supported languages. It will return the two letter code, and the name of the language both in that language and in English.

More information about AvailableLanguages, including returned results is available in the what3words REST API documentation.

what3words.available_languages

# Expected Output
# => {:languages=>[{:nativeName=>"Deutsch", :code=>"de", :name=>"German"}, {:nativeName=>"हिन्दी", :code=>"hi", :name=>"Hindi"}, {:nativeName=>"Português", :code=>"pt", :name=>"Portuguese"}, {:nativeName=>"Magyar", :code=>"hu", :name=>"Hungarian"}, {:nativeName=>"Українська", :code=>"uk", :name=>"Ukrainian"}, {:nativeName=>"Bahasa Indonesia", :code=>"id", :name=>"Bahasa Indonesia"}, {:nativeName=>"اردو", :code=>"ur", :name=>"Urdu"}, ___...___]}
Copied

Handling errors

Errors returned from the API can be caught with the wrapper through the use of a raise function.

Within the raise function, code and message values which represent the error, are accessible from the error object parameter

if response['error'].to_s.strip != ''
  raise ResponseError, "#{response['code']}: #{response['message']}"
end
Copied
6RegEx Functions

This section introduces RegEx functions that can assist with checking and finding possible what3words addresses in strings. The three main functions covered are:

  • isPossible3wa – Match what3words address format;
  • findPossible3wa – Find what3words address in Text;
  • isValid3wa – Verify a what3words address with the API;

isPossible3wa

Our API wrapper RegEx function “isPossible3wa” can be used used to detect if a text string (like “filled.count.soap“) in the format of a what3words address without having to ask the API. This functionality checks if a given string could be a what3words address. It returns true if it could be, otherwise false.

Note: This function checks the text format but not the validity of a what3words address. Use isValid3wa to verify validity.

require 'what3words'

def main
  # Initialize the What3Words API with your API key
  api_key = 'YOUR_API_KEY'
  w3w = What3Words::API.new(:key => api_key)

  # Example what3words addresses
  addresses = ["filled.count.soap", "not a 3wa", "not.3wa address"]

  # Check if the addresses are possible what3words addresses
  addresses.each do |address|
    is_possible = w3w.isPossible3wa(address)
    puts "Is '#{address}' a possible what3words address? #{is_possible}"
  end
end

if __FILE__ == $0
  main
end
Copied

Expected Output

  • isPossible3wa(“filled.count.soap”) returns true
  • isPossible3wa(“not a 3wa”) returns false
  • isPossible3wa(“not.3wa address”)returns false

findPossible3wa

Our API wrapper RegEx function “findPossible3wa” can be used to detect a what3words address within a block of text, useful for finding a what3words address in fields like Delivery Notes. For example, it can locate a what3words address in a note like “Leave at my front door ///filled.count.soap”. The function will match if there is a what3words address within the text. If no possible addresses are found, it returns an empty list.

Note:

  • This function checks the text format but not the validity of a what3words address. Use isValid3wa to verify validity.
  • This function is designed to work across languages but do not work for Vietnamese (VI) due to spaces within words.
require 'what3words'

def main
  # Initialize the what3words API with your API key
  api_key = 'YOUR_API_KEY'
  w3w = What3Words::API.new(:key => api_key)

  # Example texts
  texts = [
    "Please leave by my porch at filled.count.soap",
    "Please leave by my porch at filled.count.soap or deed.tulip.judge",
    "Please leave by my porch at"
  ]

  # Check if the texts contain possible what3words addresses
  texts.each do |text|
    possible_addresses = w3w.findPossible3wa(text)
    puts "Possible what3words addresses in '#{text}': #{possible_addresses}"
  end
end

if __FILE__ == $0
  main
end
Copied

Expected Output

  • findPossible3wa(“Please leave by my porch at filled.count.soap”) returns ['filled.count.soap']
  • findPossible3wa(“Please leave by my porch at filled.count.soap or deed.tulip.judge”) returns ['filled.count.soap', 'deed.tulip.judge']
  • findPossible3wa(“Please leave by my porch at”) returns []

isValid3wa

Our API wrapper RegEx function “isValid3wa” can be used to determine if a string is a valid what3words address by checking it against the what3words RegEx filter and verifying it with the what3words API.

require 'what3words'

def main
  # Initialize the what3words API with your API key
  api_key = 'YOUR_API_KEY'
  w3w = What3Words::API.new(:key => api_key)

  # Example addresses
  addresses = [
    "filled.count.soap",
    "filled.count.",
    "coding.is.cool"
  ]

  # Check if the addresses are valid what3words addresses
  addresses.each do |address|
    is_valid = w3w.isValid3wa(address)
    puts "Is '#{address}' a valid what3words address? #{is_valid}"
  end
end

if __FILE__ == $0
  main
end
Copied

Expected Outputs

  • isValid3wa(“filled.count.soap”) returns True
  • isValid3wa(“filled.count.”) returns False
  • isValid3wa(“coding.is.cool”) returns False

Also make sure to replace <YOUR_API_KEY> with your actual API key. These functionalities provide different levels of validation for what3words addresses, from simply identifying potential addresses to verifying their existence on Earth.

7Troubleshooting

If you encounter errors or issues related to convert-to-coordinate, convert-to-3wa and grid-section requests while using the Free plan, please check the network panel for the following error message Error 402 payment required and its response, indicating the need to upgrade to a higher plan:

{
    "error": {
        "code": "QuotaExceeded",
        "message": "Quota exceeded or API plan does not have access to this feature. Please change your plan at https://accounts.what3words.com/select-plan, or contact support@what3words.com"
    }
}
Copied

For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.

8Full example

The example below takes the concepts described above, and turns some of them into a complete example. Here we take a partial 3 word address and pass it into AutoSuggest – clipping the results to consider only addresses in Great Britain and Belgium, setting a focus, and returning a single result

We then take the result and convert the 3 word address to coordinates, and vice-versa.

# frozen_string_literal: true
#!/usr/bin/env

require 'what3words'
require 'json'

api_key = ENV['W3W_API_KEY']

what3words = What3Words::API.new(:key => api_key, :format => 'json')

# ## convert_to_coordinates #########
res = what3words.convert_to_coordinates 'prom.cape.pump'
puts '######### convert_to_coordinate #########'
puts res

# ## convert_to_3wa #########
res = what3words.convert_to_3wa [29.567041, 106.587875]
puts '######### convert_to_3wa #########'
puts res

# ## grid_section #########
res = what3words.grid_section '52.208867,0.117540,52.207988,0.116126'
puts '######### grid_section #########'
puts res

# ## available_languages #########
res = what3words.available_languages
puts '######### available_languages #########'
puts res


# ## Vanilla autosuggest, limiting the number of results to three #########
res = what3words.autosuggest 'disclose.strain.redefin', language: 'en', 'n-results': 10
puts '######### autosuggest n-results #########'
puts res

# ## autosuggest demonstrating clipping to polygon, circle, bounding box, and country #########
res_polygon = what3words.autosuggest 'disclose.strain.redefin', 'clip-to-polygon': [51.521, -0.343, 52.6, 2.3324, 54.234, 8.343, 51.521, -0.343]
res_circle = what3words.autosuggest 'disclose.strain.redefin', 'clip-to-circle': [51.521, -0.343, 142]
res_bbox = what3words.autosuggest 'disclose.strain.redefin', 'clip-to-bounding-box': [51.521, -0.343, 52.6, 2.3324]
res_country = what3words.autosuggest 'disclose.strain.redefin', 'clip-to-country': 'GB,BE'
puts '######### autosuggest clipping options #########'
puts res_polygon
puts res_circle
puts res_bbox
puts res_country

# ## autosuggest with a focus, with that focus only applied to the first result #########
res = what3words.autosuggest 'filled.count.soap', focus: [51.4243877, -0.34745], 'n-focus-results': 3,  'n-results': 10
puts '######### autosuggest with a focus ######### '
puts res

# ## autosuggest with an input type of Generic Voice #########
res =  what3words.autosuggest 'fun with code', 'input-type': 'generic-voice', language: 'en'
puts '######### autosuggest with Generic Voice as input type ######### '
puts res

# ## isPossible3wa #########
addresses = ["filled.count.soap", "not a 3wa", "not.3wa address"]
addresses.each do |address|
  is_possible = what3words.isPossible3wa(address)
  puts "Is '#{address}' a possible what3words address? #{is_possible}"
end

# ## findPossible3wa #########
texts = [
  "Please leave by my porch at filled.count.soap",
  "Please leave by my porch at filled.count.soap or deed.tulip.judge",
  "Please leave by my porch at"
]
texts.each do |text|
  possible_addresses = what3words.findPossible3wa(text)
  puts "Possible what3words addresses in '#{text}': #{possible_addresses}"
end

# ## isValid3wa #########
addresses = ["filled.count.soap", "filled.count.", "coding.is.cool"]
addresses.each do |address|
  is_valid = what3words.isValid3wa(address)
  puts "Is '#{address}' a valid what3words address? #{is_valid}"
end

Copied

Related tutorials