Skip to content

Instantly share code, notes, and snippets.

@weilu
Created May 19, 2013 03:00
Show Gist options
  • Save weilu/5606509 to your computer and use it in GitHub Desktop.
Save weilu/5606509 to your computer and use it in GitHub Desktop.
import java.util.*;
class Programmer {
private String name;
private int age;
private List<String> languages;
public Programmer(String name) {
this.name = name;
this.languages = new ArrayList<String>();
}
public void learn(String languages) {
this.languages.add(languages);
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public String toString() {
return "A programmer named " + name
+ ", " + age + " years old, knows " + languagesString() + ".";
}
private String languagesString() {
String result = Arrays.toString(languages.toArray());
return result.substring(1, result.length() - 1);
}
public static void main(String[] args) {
Programmer alice = new Programmer("Alice");
alice.setAge(8);
String[] languages = { "Java", "Ruby", "Python" };
for(int i = 0; i < languages.length; i++) {
alice.learn(languages[i]);
}
System.out.println(alice);
}
}
class Programmer # No braces, use `end` instead
attr_accessor :age # Symbol, Getter+Setter
attr_reader :name # Getter
def initialize name # Define method, Constructor, Optional parentheses
@name = name # Instance variable
@languages = [] # Array
end
def learn language
@languages << language # invoking method array<<
end
def to_s # toString, No return data type
"A programmer named #{name}, #{age} years old, knows #{languages_string}."
end # String interpolation, Optional parentheses
private
def languages_string
@languages.join(", ") # Implicit return
end
end
alice = Programmer.new('Alice') # Object initialization
alice.age = 8 # Invoking method age=
languages = %w{Java Ruby Python} # Alternative array instantiation with perl % syntax
languages.each do |language| # Iterate over an array
alice.learn language
end
puts alice # Output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment