1
class Dates
  ATTRS = {date_from: '', date_to: ''}

  def set_dates(ATTRS)
    @date_from = date_from
    @date_to   = date_to
  end

  def show_dates(ATTRS)
    p date_from
    p date_to
  end
end

Dates.new.set_dates(date_from: Time.current, date_to: Time.current)
#-:4: formal argument cannot be a constant
#  def set_dates(ATTRS)
#                     ^
#-:9: formal argument cannot be a constant
#  def show_dates(ATTRS)

SO question is: Is it possible to store method attributes in variable ?

3
  • 1
    change to def set_dates(ATTRS) to def set_dates(**args). This is keyword arguments. Commented Mar 4, 2014 at 9:48
  • 1
    you right, i totally forgot about it, thanks, issue the answer. Commented Mar 4, 2014 at 9:52
  • release my answer, I will down it... Commented Mar 4, 2014 at 10:18

2 Answers 2

4

You can use the new keyword arguments syntax in Ruby 2.0:

class Dates
  def set_dates(date_from: '', date_to: '')
    @date_from = date_from
    @date_to = date_to
  end
  def show_dates
    p @date_from
    p @date_to
  end
end

Or the hash arguments before Ruby 2.0:

class Dates
  ATTRS = {date_from: '', date_to: ''}
  def set_dates(attr)
    attr = ATTRS.merge(attr)
    @date_from = attr[:date_from]
    @date_to = attr[:date_to]
  end
  def show_dates
    p @date_from
    p @date_to
  end
end

For the show_dates method, I guess you meant showing the status of the Dates instance, so I made some modification to it.

Besides, in Ruby, variables started with capitalized letter are treated as constants, you cannot use it as formal arguments of the methods.

Sign up to request clarification or add additional context in comments.

Comments

2

I would write your code as below using Ruby (2.0.0 > =) new keyword rest argument(**) operator :

class Dates
  def set_dates(**attr)
    @date_from,@date_to = attr.values_at(:date_from,:date_to)
  end

  def show_dates
    p @date_from
    p @date_to
  end
end

5 Comments

Where are the keyword arguments in your example?
The return value of Hash#values may be in arbitrary order. I think you shouldn't make assumptions that the value associated with :date_from comes first.
@apneadiving I will down it.. wait
@Agis What **attr is doing then ?
You are confusing the keywords arguments feature introduced in Ruby 2.0 with just expanding a hash argument. You're just accepting a hash no matter its contents are and assume that it has the wanted keys. This is not what keyword arguments is about. See @Arie Shaw answer, his method will raise an error if the proper arguments aren't passed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.