Skip to content

Instantly share code, notes, and snippets.

@mdominiak
Last active October 22, 2018 14:32
Show Gist options
  • Save mdominiak/4673012 to your computer and use it in GitHub Desktop.
Save mdominiak/4673012 to your computer and use it in GitHub Desktop.
Ruby vs. Java comparison
Ruby is terse. Getters and setters example.
Java:
Class Circle {
private Coordinate center, float radius;
public void setCenter(Coordinate center) {
this.center = center;
}
public Coordinate getCenter() {
return center;
}
public void setRadius(float radius) {
this.radius = radius;
}
public float getRadius() {
return radius;
}
}
Ruby:
class Circle
attr_accessor :center, :radius
end
Ruby uses dynamic typing (values have type, variables not), which decreases language complexity (no type declaration, no type casting) and increases flexibility.
Java:
public static int len(List list) {
int x = 0;
Iterator listIterator = list.iterator();
while (listIterator.hasNext()) {
x += 1
}
return x;
}
Ruby:
def len(list)
x = 0;
list.each do |element|
x += 1;
end
x
end
Playing with lists.
Java:
List<String> languages = new LinkedList<String>();
languages.add("Java");
langauges.add("Ruby");
languages.add("Python);
Ruby:
languages = ["Java", "Ruby", "Python"]
# or
languages = %w{Java Ruby Python}
Simple iteration.
Java:
for (int i = 1; i <= 100; i++) {
System.out.println(i);
}
Ruby:
for i in 1..100 do
puts i
end
Everything is a object in Ruby.
Ruby:
1.class # => Fixnum
Core classes can be extended easily in Ruby.
Ruby:
class Fixnum
def +(i)
self - 1
end
end
1 + 1 # => 0
Ruby metaprogramming.
speaker = Class.new
speaker.class_eval do
def speak
puts "Hello World"
end
end
instance = speaker.new
instance.speak
# => Hello World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment