# Ruby

### Installing the Ruby Gem

A [Hosted Graphite Ruby Gem](https://rubygems.org/gems/hosted_graphite) is available on github, and can be installed directly by typing:

```ruby
gem install hosted_graphite
```

### Using the Gem to send via TCP

```ruby
HostedGraphite.protocol = HostedGraphite::TCP
HostedGraphite.send_metric('foo.rb-tcp', 1.2)
```

### Using the Gem to send via UDP

```ruby
HostedGraphite.protocol = HostedGraphite::UDP
HostedGraphite.send_metric('foo.rb-udp', 1.2)
```

### Using the Gem to send via HTTP

```ruby
HostedGraphite.protocol = HostedGraphite::HTTP
HostedGraphite.send_metric('foo.rb-http', 1.2)
```

### Using the Gem to send via StatsD

```ruby
require 'hosted_graphite'
require 'statsd-ruby'

HostedGraphite.api_key = '<your-api-key>'
HostedGraphite.protocol = :statsd
HostedGraphite.<gauge-count-or-timing>('foo.rb-statsd', 1.2)
```

### Basic Ruby

Here are some ways to send custom metric via TCP, UDP, HTTP, and StatsD directly from your code.

### Sending a metric via TCP

```ruby
require 'socket'

conn = TCPSocket.new 'YOUR-UID.carbon.hostedgraphite.com', 2003
conn.puts "YOUR-API-KEY.foo 1.2\n"
conn.close
```

### Sending a metric via UDP

```ruby
require 'socket'

sock = UDPSocket.new
sock.send "YOUR-API-KEY.foo 1.2\n", 0, "YOUR-UID.carbon.hostedgraphite.com", 2003
```

### Sending a metric via HTTP POST

```ruby
require 'net/http'

uri = URI("https://www.hostedgraphite.com/api/v1/sink")
api_key = "YOUR-API-KEY"

req = Net::HTTP::Post.new(uri.request_uri)
req.basic_auth api_key, nil
req.body = "foo 1.2"

res = Net::HTTP.start(uri.host, uri.port) do |http|
  http.request(req)
end
```

### Sending a metric via StatsD

```ruby
require 'socket'

statsd_host = 'statsd.hostedgraphite.com'
statsd_port = 8125
metric_key = 'YOUR-API-KEY.foo.ruby-statsd'
metric_value = 1.2

metric_message = "#{metric_key}:#{metric_value}|<c/g/ms>"

sock = UDPSocket.new
sock.send(metric_message, 0, statsd_host, statsd_port)
sock.close
```

**NOTE**: when sending standard ruby StatsD metrics, be sure to define counters (c), gauges (g), or timers (ms).

Your API key can be found on your [account home](https://www.hostedgraphite.com/accounts/profile/) page.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hostedgraphite.com/language-guide/ruby.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
