Ruby equivalent to Python's help()?
It's definitely a poor cousin to iPython's help, and one of the main features I miss after moving to Ruby, but you can also use ri
from within irb
. I'd recommend the wirble gem as an easy way to set this up.
Ruby equivalent of Python's `repr()`?
Based on the helpful comments from jeremy04
and Jörg W Mittag
, I realize that there is nothing in Ruby which corresponds to repr
, and that I can't make use of a simple repr
-like method in all class instances without monkey-patching class Object
itself. However, I realize that if I just make repr
a standalone function, I can get the same functionality without monkey-patching and by doing repr(obj)
instead of obj.repr
whenever I want this info for a given object. The following stand-alone function works ...
def repr(obj)
attrhash = {}
obj.instance_variables.sort.each {
|v|
attrhash[v] = instance_variable_get(v)
}
{
:string => obj.inspect,
:methods => obj.class.instance_methods.sort,
:attributes => attrhash
}
end
I have this function return a hash instead of a string so that I can do things like this:
repr(obj)[:attributes]
.
I can always do repr(obj).to_s
if I want a string.
Also, I could make this into a class. I'll leave that as an exercise for the reader. :)
Python's equivalent of Ruby's ||=
I think there is some confusion from the people who aren't really sure what the conditional assignment operator (||=
) does, and also some misunderstanding about how variables are spawned in Ruby.
Everyone should read this article on the subject. A TLDR quote:
A common misconception is that a ||= b is equivalent to a = a || b, but it behaves like a || a = b
In a = a || b, a is set to something by the statement on every run, whereas with a || a = b, a is only set if a is logically false (i.e. if it's nil or false) because || is 'short circuiting'. That is, if the left hand side of the || comparison is true, there's no need to check the right hand side.
And another very important note:
...a variable assignment, even if not run, immediately summons that variable into being.
# Ruby
x = 10 if 2 == 5
puts x
Even though the first line won't be run, x will exist on the second line and no exception will be raised.
This means that Ruby will absolutely ensure that there is a variable container for a value to be placed into before any righthand conditionals take place. ||=
doesn't assign if a
is not defined, it assigns if a
is falsy (again, false
or nil
- nil
being the default nothingness value in Ruby), whilst guaranteeing a
is defined.
What does this mean for Python?
Well, if a
is defined, the following:
# Ruby
a ||= 10
is actually equivalent to:
# Python
if not a:
a = 10
while the following:
# Either language
a = a or 10
is close, but it always assigns a value, whereas the previous examples do not.
And if a
is not defined the whole operation is closer to:
# Python
a = None
if not a:
a = 10
Because a very explicit example of what a ||= 10
does when a
is not defined would be:
# Ruby
if not defined? a
a = nil
end
if not a
a = 10
end
At the end of the day, the ||=
operator is not completely translatable to Python in any kind of 'Pythonic' way, because of how it relies on the underlying variable spawning in Ruby.
Does Ruby have a dir method, similar to Python?
There is fairly popular gem pry, which has method called ls
that can provide you I believe with something, similar to the dir
in Python.
Ruby equivalent to Python __main__
I believe this will work:
if __FILE__ == $0
tell_the_truth()
end
What does Ruby have that Python doesn't, and vice versa?
You can have code in the class definition in both Ruby and Python. However, in Ruby you have a reference to the class (self). In Python you don't have a reference to the class, as the class isn't defined yet.
An example:
class Kaka
puts self
end
self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python.
Python equivalent of Ruby's .find
Below code in python for your ruby logic.
CF={"metre":{"kilometre":0.001, "metre":1.0, "centimetre":100.0}, "litre":{"litre":1.0, "millilitre":1000.0, "imperial_pint":1.75975}}
def common(fr,to):
for key,value in CF.items():
if (fr in value) and (to in value):
return key
print(common('metre','centimdetre'))
metre
print(com('metre','centimdetre'))
None
******************
single line function
com = lambda x,y:[key for key,value in CF.items() if (x in value) and (y in value)]
print(com('metre','centimdetre'))
['metre']
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'
Python's equivalent for Ruby's define_method?
Functions are first-class objects in Python and can be assigned to attributes of a class or an instance. One way to do the same thing as in the Wikipedia example is:
colours = {"black": "000",
"red": "f00",
"green": "0f0",
"yellow": "ff0",
"blue": "00f",
"magenta": "f0f",
"cyan": "0ff",
"white": "fff"}
class MyString(str):
pass
for name, code in colours.iteritems():
def _in_colour(self, code=code):
return '<span style="color: %s">%s</span>' % (code, self)
setattr(MyString, "in_" + name, _in_colour)
Related Topics
Force Python to Forego Native SQLite3 and Use the (Installed) Latest SQLite3 Version
Get Human Readable Version of File Size
Wtforms, Add a Class to a Form Dynamically
How to Convert R Dataframe Back to Pandas Using Rpy2
Size Legend for Plotly Bubble Map/Chart
Efficient Ways to Duplicate Array/List in Python
Scripting Http More Effeciently
Iterate Over Object Attributes in Python
How to Override the Copy/Deepcopy Operations for a Python Object
How to Operate on a Dataframe with a Series for Every Column
Stream Large Binary Files with Urllib2 to File
Efficiently Convert Uneven List of Lists to Minimal Containing Array Padded with Nan
How to Use a Socks 4/5 Proxy with Urllib2
Parameterized Queries with Psycopg2/Python Db-API and Postgresql