それPy

先日、 Rubyのホームページ がリニューアルしました。上のほうに“エレガントな文法を持ち、自然に読み書きができます。”とあって、特徴的なサンプルコードが載っています。 それPythonだとこうなるよ! ってことで、書いてみました。やっぱり、RubyとPythonって似てるなぁ…

(1)Rubyの場合

# The Greeter class
class Greeter
  def initialize(name)
    @name = name.capitalize
  end

  def salute
    puts "Hello #{@name}!"
  end
end

# Create a new object
g = Greeter.new("world")

# Output "Hello World!"
g.salute

(1)Pythonの場合

# The Greeter class
class Greeter:
    def __init__(self, name):
        self.name = name.capitalize()

    def salute(self):
        print "Hello %s!" % self.name

# Create a new object
g = Greeter('world')

# Output "Hello World!"
g.salute()

(2)Rubyの場合

cities  = %w[ London
              Oslo
              Paris
              Amsterdam
              Berlin ]
visited = %w[Berlin Oslo]

puts "I still need " +
     "to visit the " +
     "following cities:",
     cities - visited

(2)Pythonの場合

cities = set(['London',
              'Oslo',
              'Paris',
              'Amsterdam',
              'Berlin'])
visited = set(['Berlin', 'Oslo'])

print "I still need to visit the following cities:", \
      cities - visited

(3)Rubyの場合

# Output "I love Ruby"
say = "I love Ruby"
puts say

# Output "I *LOVE* RUBY"
say['love'] = "*love*"
puts say.upcase

# Output "I *love* Ruby"
# five times
5.times { puts say }

(3)Pythonの場合

# Output "I love Python"
say = "I love Python"
print say

# Output "I *LOVE* PYTHON"
say = say.replace("love", "*love*")
print say.upper()

# Output "I *love* Python"
# five times
print say * 5


Leave a comment


:

:

:

:

このエントリーのはてなブックマーク (-)