

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用適用於 Ruby 的 AWS SDK 建立簡單的應用程式
<a name="hello"></a>

使用適用於 Ruby 的 AWS SDK 向 Amazon S3 打招呼。下列範例顯示 Amazon S3 儲存貯體的清單。

## 編寫程式碼
<a name="aws-ruby-sdk-hello-world-code"></a>

將下列程式碼複製並貼到新的來源檔案中。將檔案命名為 `hello-s3.rb`。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 resource actions.
class BucketListWrapper
  attr_reader :s3_resource

  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def initialize(s3_resource)
    @s3_resource = s3_resource
  end

  # Lists buckets for the current account.
  #
  # @param count [Integer] The maximum number of buckets to list.
  def list_buckets(count)
    puts 'Found these buckets:'
    @s3_resource.buckets.each do |bucket|
      puts "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't list buckets. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  wrapper = BucketListWrapper.new(Aws::S3::Resource.new)
  wrapper.list_buckets(25)
end

run_demo if $PROGRAM_NAME == __FILE__
```

AWS 適用於 Ruby 的 SDK 設計為模組化，並以 分隔 AWS 服務。安裝 Gem 套件後，Ruby 來源檔案頂端的 `require`陳述式會匯入 Amazon S3 服務的 AWS SDK 類別和方法。如需可用 AWS 服務 Gem 的完整清單，請參閱適用於 Ruby README 檔案的 AWS SDK [支援服務](https://github.com/aws/aws-sdk-ruby/#supported-services)資料表。

```
require 'aws-sdk-s3'
```

## 執行程式
<a name="aws-ruby-sdk-hello-world-running"></a>

開啟命令提示以執行 Ruby 程式。執行 Ruby 程式的典型命令語法為：

```
ruby [source filename] [arguments...]
```

此範例程式碼不使用引數。若要執行此程式碼，請在命令提示中輸入以下內容：

```
$ ruby hello-s3.rb
```

## Windows 使用者的注意事項
<a name="aws-ruby-sdk-quick-start-windows"></a>

當您在 Windows 上使用 SSL 憑證並執行 Ruby 程式碼時，您可能會看到類似以下的錯誤。

```
C:\Ruby>ruby buckets.rb
C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (Seahorse::Client::NetworkingError)
         from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `block in connect'

         from C:/Ruby200-x64/lib/ruby/2.0.0/timeout.rb:66:in `timeout'
         from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect'
         from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:862:in `do_start'
         from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:857:in `start'
...
```

若要修正此問題，請在第一次 AWS 呼叫之前某個位置，將以下行新增至 Ruby 來源檔案。

```
Aws.use_bundled_cert!
```

如果您在 Ruby 程式中僅使用 `aws-sdk-s3` Gem 套件，並且想要使用綁定憑證，則還需要新增 `aws-sdk-core` Gem 套件。

## 後續步驟
<a name="aws-ruby-sdk-hello-world-next-steps"></a>

若要測試許多其他 Amazon S3 操作，請查看 GitHub 上的[AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/example_code//s3)。