Skip to content

Instantly share code, notes, and snippets.

@brikis98
Created January 29, 2012 22:11
Show Gist options
  • Save brikis98/1700969 to your computer and use it in GitHub Desktop.
Save brikis98/1700969 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks: Ruby, Day 2
class Integer
def times
1.upto(self) { yield }
end
end
arr = (1..16).to_a
arr.each { |i| print "#{i}#{i % 4 == 0 ? "\n" : ','}" }
arr = (1..16).to_a
arr.each_slice(4) { |slice| puts slice.join(", ") }
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Usage: java Grep <regular_expression> <file_name>
*/
public class Grep {
public static void main(String[] args) throws IOException {
Pattern pattern = Pattern.compile(args[0]);
BufferedReader br = null;
String line = null;
int lineNumber = 1;
try {
br = new BufferedReader(new FileReader(new File(args[1])));
while((line = br.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println(lineNumber + ": " + line);
}
lineNumber++;
}
} finally {
if (br != null) {
br.close();
}
}
}
}
# Usage: ruby grep.rb <regular_expression> <file_name>
IO.readlines(ARGV[1]).each_with_index{ |line, index| puts "#{index + 1}: #{line}" if line =~ /#{ARGV[0]}/}
return _transactionManager.execute(new VoidDBExecCallback() {
public void doExecute(DBExecContext dbExecContext) throws TransactionException {
dbExecContext.getJdbcTemplate().execute(
"Select name from tbl_foo where id = ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException
{
ps.setInt(1, 12345);
}
},
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException
{
String name = rs.getString(1);
}
}
);
}
});
within_a_transaction { do_something }
within_a_transaction do
do_something
do_something_else
do_a_third_thing
end
def within_a_transaction
start_transaction
yield
end_transaction
end
class Tree
attr_accessor :children, :node_name
def initialize(tree = {})
@node_name = tree.keys[0]
@children = tree[@node_name].collect{ |k, v| Tree.new({k => v}) }
end
def visit_all(&block)
visit &block
children.each { |c| c.visit_all &block }
end
def visit(&block)
block.call self
end
end
tree = Tree.new({"grandpa" => {"dad" => {"child1" => {}, "child2" => {}}, "uncle" => {"child3" => {}, "child4" => {}}}})
tree.visit_all { |node| puts node.node_name }
class Tree
attr_accessor :children, :node_name
def initialize(name, children = [])
@children = children
@node_name = name
end
def visit_all(&block)
visit &block
children.each { |c| c.visit_all &block }
end
def visit(&block)
block.call self
end
end
tree = Tree.new("Ruby", [Tree.new("Reia"), Tree.new("MacRuby")])
tree.visit_all { |node| puts node.node_name }
@brikis98
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment