SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: default value in methods
-
May 1, 2006, 07:48 #1
- Join Date
- Jun 2004
- Location
- France
- Posts
- 129
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
default value in methods
hi,
I have problems with default values. I don't know whether I'm stupid or doc is not good (you're not supposed to answer) but I spend a lot of time for trivial things.
According to Wiki RailsBestPractices, it's a good idea to add a default value like that:
PHP Code:def self.custom_find( id_to_find = 1 )
...
end
[edit: the query is ok without = 0 default value ]
PHP Code:def self.find_query(category, type, city_id, price_min = 0, price_max)
find(:all,
sql conditions coming here...)
end
Did I miss something?
-
May 1, 2006, 09:21 #2
- Join Date
- Aug 2005
- Posts
- 986
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Only the last parameters can have default values. How would you call it otherwise?
find_querycat, :type, :city_id, ????, 100)
??
So ruby is expecting the last parameter to have a default value too. That's why it needs a =, instead of ):
Code:def self.find_query(category, type, city_id, price_min = 0, price_max = 100000) ^ =, not )
-
May 1, 2006, 09:59 #3
- Join Date
- Jun 2004
- Location
- France
- Posts
- 129
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
thanks Fenrir2, it works but I find it weird as it's not mandatory, just a best practice.
Plus it's not used when the value is empty, it seems to work only with null values.
-
May 1, 2006, 10:41 #4
- Join Date
- Aug 2005
- Posts
- 986
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
It's there so you can omit these arguments if you call your procedure. It is by no means a best practice, there are special cases where it is handy. Only use default values if it makes sense.
It is there so you can call your procedure this way:
Code:Foo.find_query(a_category, a_type, a_city_id)
You cannot do this for a parameter in the middle because it makes no sense to omit it if you have parameters after it.
Another use case is Rails' find. You can use:
Foo.find(23) => find row with id=23
And:
Code:Foo.find(:first, :conditions => 'a = "b"')
-
May 2, 2006, 02:37 #5
- Join Date
- Jun 2004
- Location
- France
- Posts
- 129
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
thanks for the tips Fenrir2
Bookmarks