Ruby Methods and Optional parameters

后端 未结 11 1607

I\'m playing with Ruby on Rails and I\'m trying to create a method with optional parameters. Apparently there are many ways to do it. I trying naming the optional parameters

11条回答
  •  鱼传尺愫
    2020-12-13 10:05

    I don't see anything wrong with using an or operator to set defaults. Here's a real life example (note, uses rails' image_tag method):

    file:

    def gravatar_for(user, options = {} )   
        height = options[:height] || 90
        width = options[:width] || 90
        alt = options[:alt] || user.name + "'s gravatar"
    
        gravatar_address = 'http://1.gravatar.com/avatar/'
    
        clean_email = user.email.strip.downcase 
        hash = Digest::MD5.hexdigest(clean_email)
    
        image_tag gravatar_address + hash, height: height, width: width, alt: alt 
    end
    

    console:

    2.0.0-p247 :049 > gravatar_for(user)
     => "\"jim's\" width=\"90\" />" 
    2.0.0-p247 :049 > gravatar_for(user, height: 123456, width: 654321)
     => "\"jim's\" width=\"654321\" />" 
    2.0.0-p247 :049 > gravatar_for(user, height: 123456, width: 654321, alt: %[dogs, cats, mice])
     => "\"dogs\" width=\"654321\" />" 
    

    It feels similar to using the initialize method when calling a class.

提交回复
热议问题