

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用适用于 Ruby 的 AWS SDK 创建简单应用程序
<a name="hello"></a>

使用适用于 Ruby 的 S AWS DK 向亚马逊 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 的完整列表，请参阅 AWS SDK for Ruby README 文件的 “[支持的服务](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 操作，请查看上的 “[AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/example_code//s3)” GitHub。