如何使用方法的字符串参数作为方法名称变量

use*_*963 1 ruby ruby-on-rails

在我的rails应用程序中,我使用了carrierwave图像.Carrierwave创建不同版本的图像的,并且可以这样获得的网址:picture.large.url,picture.small.url,picture.thumb.url,等.

我想创建一个方法,可以接受一个字符串参数,然后可以用于图像URL.像这样的东西:

def profile_url (version)
  picture.version.url
end
Run Code Online (Sandbox Code Playgroud)

那么我可以写@user.profile_url('thumb'),它应该给我拇指大小的网址.

我得到一个未定义的方法'版本'错误.这可能吗?

tad*_*man 6

通常你可以这样做:

def profile_url(version)
  version = version.to_sym

  case version
  when :large, :small, :thumb
    picture.send(version).url
  end
end
Run Code Online (Sandbox Code Playgroud)

to_sym这里打电话的原因是你可以打电话给这个profile_url('thumb')profile_url(:thumb)两者都可以.