Sample code for 30+ languages & platforms
Ruby

Google Translate Text

See more Google Translate Examples

Demonstrates how to use the Cloud Translation API to translate text from one spoken language to another. The example translates from English to Spanish.

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

# This example assumes the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

# --------------------------------------------------------------------------------
# IMPORTANT: 
# Don't forget you need to 1st enable the Cloud Translation API in your Google Developers Console at https://console.cloud.google.com
# --------------------------------------------------------------------------------

# It is assumed we previously obtained an OAuth2 access token.
# This example loads the JSON access token file 
jsonToken = Chilkat::CkJsonObject.new()
success = jsonToken.LoadFile("qa_data/tokens/_googleTranslate.json")
if (success != true)
    print "Failed to load _googleTranslate.json" + "\n";
    exit
end

http = Chilkat::CkHttp.new()

http.put_AuthToken(jsonToken.stringOf("access_token"))

# The following JSON is sent in the request body.

# {
#     "q": "The quick brown fox jumped over the lazy dog.",
#     "source": "en",
#     "target": "es",
#     "format": "text"
# }

json = Chilkat::CkJsonObject.new()
# The following code creates the JSON request body.
json.UpdateString("q","The quick brown fox jumped over the lazy dog.")
json.UpdateString("source","en")
json.UpdateString("target","es")
json.UpdateString("format","text")

json.put_EmitCompact(false)
print json.emit() + "\n";

resp = Chilkat::CkHttpResponse.new()
success = http.HttpJson("POST","https://translation.googleapis.com/language/translate/v2",json,"application/json",resp)
if (success == false)
    print http.lastErrorText() + "\n";
    exit
end

jResp = Chilkat::CkJsonObject.new()
resp.GetBodyJson(jResp)
jResp.put_EmitCompact(false)

print "Response Body:" + "\n";
print jResp.emit() + "\n";

respStatusCode = resp.get_StatusCode()
print "Response Status Code = " + respStatusCode.to_s() + "\n";
if (respStatusCode >= 400)
    print "Response Header:" + "\n";
    print resp.header() + "\n";
    print "Failed." + "\n";
    exit
end

# Sample JSON response:
# (Sample code for parsing the JSON response is shown below)

# {
#   "data": {
#     "translations": [
#       {
#         "translatedText": "El zorro r�pida salt� sobre el perro perezoso."
#       }
#     ]
#   }
# }

i = 0
n = jResp.SizeOfArray("data.translations")
while i < n
    jResp.put_I(i)
    translatedText = jResp.stringOf("data.translations[i].translatedText")
    print translatedText + "\n";
    i = i + 1
end