What is the ruby equivalent of python's getattr
The equivalent statement in Ruby:
date_wanted = :created_on
title_date = list_titles.send(date_wanted)
Ruby equivalent of Python setattr()
Either obj.instance_variable_set("@instance_variable", value)
or obj.send("instance_variable=", value)
.
The former directly sets the instance variable. The latter calls the setter method, which of course only works if there is a setter method, but on the other hand also works if you have a setter method that doesn't actually only set an instance variable (or doesn't set an instance variable at all).
PHP equivalent of send and getattr?
PHP brings this:
$foobarobject->{"foomethod"}();
... and the coke and chips.
EDIT:
Although the term for the above is variable variables
there is nothing specifically talking about doing it to an object in the manual. However, you can achieve the same thing with call_user_func
:
call_user_func(array($foobarobject, "foomethod"));
Python equivalent for Ruby's ObjectSpace?
globals()[classname]
should do it.
More code: http://code.activestate.com/recipes/285262/
Pythons getattr in Ruby
In Ruby:
class Test
def say(word)
word
end
end
test = Test.new
test.send(:say, "something") #=> "something"
Is there a Python equivalent to Ruby's respond_to?
Hmmm .... I'd think that hasattr
and callable
would be the easiest way to accomplish the same goal:
class Fun:
def hello(self):
print 'Hello'
hasattr(Fun, 'hello') # -> True
callable(Fun.hello) # -> True
You could, of course, call callable(Fun.hello)
from within an exception handling suite:
try:
callable(Fun.goodbye)
except AttributeError, e:
return False
As for introspection on the number of required arguments; I think that would be of dubious value to the language (even if it existed in Python) because that would tell you nothing about the required semantics. Given both the ease with which one can define optional/defaulted arguments and variable argument functions and methods in Python it seems that knowing the "required" number of arguments for a function would be of very little value (from a programmatic/introspective perspective).
Python equivalent of Ruby's 'method_missing'
There is no difference in Python between properties and methods. A method is just a property, whose type is just instancemethod
, that happens to be callable (supports __call__
).
If you want to implement this, your __getattr__
method should return a function (a lambda
or a regular def
, whatever suite your needs) and maybe check something after the call.
From Ruby to Python - Is there an equivalent of try ?
Dictionaries: dict.get
You can use dict.get
:
d = {'foo' : 'bar'}
print(d.get('foo'))
'bar'
print(d.get('xxxxx'))
None
You can also pass a default parameter to get
:
print(d.get('xxxxx', 'Invalid Key!'))
Invalid Key!
The default value is printed out when the key does not exist in the dictionary.
Lists: custom try
-except
block
Unfortunately, lists do not have a dict.get
equivalent in their API, so you'll need to implement one yourself. Thankfully, you can extend the list
class and override __getitem__
to do this cleanly.
class MyList(list):
def __getitem__(self, idx, default='oops'):
try:
return super().__getitem__(idx)
except IndexError:
return default
l = MyList([10, 20])
l[1]
# 20
l[3]
# 'oops'
Related Topics
How to Express Infinity in Ruby
How to Format This International Phone Number in Rails
How to Convert a Ruby Object to JSON
How to Pass Data from a Controller to a Model with Ruby on Rails
How to Implement This Post Request Using Httparty
How to Extract the Code from a Proc Object
Check If an Array Is Subset of Another Array in Ruby
Dry Way to Assign Hash Values to an Object
Where Should My Non-Model/Non-Controller Code Live
Converting a Hash into a Nested Hash
Use Rvm to Force Specific Ruby in Xcode Run Script Build Phase
Reflection on Method Parameters in Ruby
When to Use Nested Classes and Classes Nested in Modules
Ruby and Linux, Preferred Setup