C#とRubyの対比・比較表、いわゆるチートシートです。 「C#で言うところの…」と「Rubyで言うところの…」に対応する記述・クラス等を対比表としてまとめたものです。 Rubyスクリプトを書いているときに「C#で言うところのアレはRubyではどう書くんだっけ」ということが多いので、すぐに参照できるようよく使う部分を中心にまとめてあります。

  • 全般的なこと
    • すべてが完全に一致するものではなく、ある程度似た動作をするものを記述している箇所があります
    • 引数や記述を一部省略しているので、そういう部分はニュアンスで読んでください
    • メソッドがクラス/インスタンスかどうか(Rubyでは破壊的/非破壊的かどうか)はあまり区別せずに記述しています
    • 特に対応するものが無い場合は空欄にしてあります
  • C#について
    • C# 3.0、.NET Framework 2.0(と一部Mono 2.4)をベースに書いています
  • Rubyについて
    • Ruby 1.8をベースに書いています
  • 関連するページ

基本

エントリポイント・コマンドライン引数

using System;

class HelloWorld {
  public static void Main(string[] args) {
    Console.WriteLine("Hello, world");

    for (var i = 0; i < args.Length; i++) {
      Console.WriteLine("{0}: {1}", i, args[i]);
    }
  }
}
#!/usr/bin/env ruby

print "Hello, world\n"

ARGV.length.times do |i|
  print "#{i}: #{ARGV[i]}\n"
end

クラス

関連するドキュメント
MSDN Rubyリファレンス
クラス (C#プログラミングガイド)
メンバ (C#プログラミングガイド)
クラス/メソッドの定義
FAQ::クラス、モジュール
FAQ::メソッド
using System;
using System.Collections.Generic;

class SomeClass {
  public int[] Values { get; set; }

  private string readOnlyValue;

  public string ReadOnlyValue {
    get { return readOnlyValue; }
  }

  public SomeClass(string val)
  {
    readOnlyValue = val;
  }

  public IEnumerator<string> GetEnumerator()
  {
    yield return "foo";
    yield return "bar";
    yield return readOnlyValue;
  }

  public void ForEach(Action<int> action)
  {
    foreach (var val in Values) {
      action(val);
    }
  }

  public override string ToString()
  {
    return "instance of SomeClass";
  }

  public static void Main()
  {
    var inst = new SomeClass("baz");

    Console.WriteLine(inst);

    inst.Values = new int[] {1, 2, 3};

    foreach (var val in inst) {
      Console.WriteLine(val);
    }

    inst.ForEach(delegate(int val) {
      Console.WriteLine(val * 3);
    });
  }
}
 GetEnumerator()
  {
    yield return "foo";
    yield return "bar";
    yield return readOnlyValue;
  }

  public void ForEach(Action action)
  {
    foreach (var val in Values) {
      action(val);
    }
  }

  public override string ToString()
  {
    return "instance of SomeClass";
  }

  public static void Main()
  {
    var inst = new SomeClass("baz");

    Console.WriteLine(inst);

    inst.Values = new int[] {1, 2, 3};

    foreach (var val in inst) {
      Console.WriteLine(val);
    }

    inst.ForEach(delegate(int val) {
      Console.WriteLine(val * 3);
    });
  }
}]]>
class SomeClass
  include Enumerable

  @values
  attr_accessor :values

  @readonly_value
  attr_reader :readonly_value

  def initialize(val)
    @readonly_value = val
  end

  def each
    yield 'foo'
    yield 'bar'
    yield @readonly_value
  end

  def foreach(&b)
    @values.each do |val|
      yield val
    end
  end

  def to_s
    return 'instance of SomeClass'
  end
end

inst = SomeClass.new('baz')
inst.values = [1, 2, 3]

print "#{inst}\n"

inst.each do |val|
  print "#{val}\n"
end

inst.foreach do |val|
  print "#{val * 3}\n"
end

コメント

/*
 * multiline comment
 */

// single line comment
Console.WriteLine("Hello, world");
=begin

 multiline comment

=end

# single line comment
print "Hello, world\n"

ヒアドキュメント

C#
string str = @"line1
line2
line3";
Ruby
str = <<END_OF_STR
line1
line2
line3
END_OF_STR

コマンドラインでの実行

Mono C# Shellを使用。

C#
$ csharp 
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> Console.WriteLine("Hello, world"); 
Hello, world
csharp> quit;
null
Ruby
$ ruby -e 'print "Hello, world\n"'
Hello, world

文字列

関連するドキュメント
MSDN Rubyリファレンス
System.String
System.Text
String
C# Ruby
C# Ruby
String.IsNullOrEmpty(str) str.nil? or str.empty?
str.to_s.empty? (nil.to_sが''となる仕様に基づく)
String.Length == 0 String.empty?
String.IndexOf String.index
String.StartsWith("foo") String =~ /^foo/
String.EndsWith("foo") String =~ /foo$/
String.ToUpper, String.ToUpperInvariant String.upcase
String.ToLower, String.ToLowerInvariant String.downcase
String.Contains, String.IndexOf != -1 String.include?
String.Replace("foo", "bar") String['foo'] = 'bar'
String.sub('foo', 'bar')
String.Replace("foo", "bar") String.gsub('foo', 'bar')
TextReader.ReadLine String.chomp
String.chop
int.Parse String.to_i
float.Parse String.to_f
String.Copy(String) String.dup
String.count('foo')
String.Trim String.strip
String.TrimStart String.lstrip
String.TrimEnd String.rstrip
new String('f', n) 'f' * n
'foo' * n
String.Split String.split
String.slice
String.Substring(index, len) String[index, len]
String.Substring(from, to - from) String[from..to]
String.Empty.Equals String.empty?
String.Format sprintf
String.Format("{0} {1}", foo, bar) "#{foo} #{bar}"
Encoding.GetString, StreamReader.Read, etc. String.unpack
Encoding.GetEncoding("shift_jis").GetString(
Encoding.Unicode.GetBytes(String))
String.tosjis (Kconv)

正規表現

関連するドキュメント
MSDN Rubyリファレンス
System.Text.RegularExpressions
.NET Framework の正規表現
Regexp
正規表現
C# Ruby
C# Ruby
Regex.IsMatch, Regex.Match =~ /.../
Regex.Matches String.scan(Regexp)
match = Regex.Match(str) match = /.../.match(str)
Regex.Replace(String, 'foo') String.gsub(Regexp, 'foo')
Regex.Replace(String, 'foo', 1) String.sub(Regexp, 'foo')
Match.Groups[0] $&
Match.Groups[1], Match.Groups[2], Match.Groups[3]... $1, $2, $3...
Match.Groups[n] $~[n]
Match.Groups[n].Captures[m]

キャプチャした文字列の参照

C#の

var match = Regex.Match("foo,bar,baz", "((.*?)(?:,|$))*");

Console.WriteLine(match.Groups[2].Captures[0].Value);
Console.WriteLine(match.Groups[2].Captures[1].Value);
Console.WriteLine(match.Groups[2].Captures[2].Value);

に相当するコード。

captures = 'foo,bar,baz'.scan(/(.*?)(?:,|$)/)

print "#{captures[0]}\n"
print "#{captures[1]}\n"
print "#{captures[2]}\n"

リスト・コレクション

関連するドキュメント
MSDN Rubyリファレンス
System.Array
System.Collections.Generic
Array
C# Ruby
C# Ruby
new[] {0, 1, 2, 3, 4} [0, 1, 2, 3, 4]
foreach (var item in array) for item in array
foreach (var item in array) array.each
List[0] Array.first
List[List.Count - 1] Array.last
List.Count Array.length, Array.size
List.Count == 0 Array.empty?
List.FindAll(Predicate<T>(T item) {return item != null;}).Length Array.nitems
List.FindIndex(Predicate<T>(T item)) {...} Array.index {|item| ...}
List.CopyTo, Array.CopyTo array.dup, array.clone
Stack.Push, List.Add Array.push
Stack.Pop Array.pop
Queue.Enqueue, List.Insert(0, item) Array.unshift
Queue.Dequeue Array.shift
List.Add('foo') Array << 'foo'
List.AddRange(new[] {0, 1, 2}) Array.concat([0, 1, 2])
List.GetRange(start, length) Array.slice(start, length)
List.RemoveAll(delegate(T item) {return item == 'foo';}) Array.delete('foo')
List.Sort Array.sort
List.Sort(Comparison<T>(T x, T y)) {...} Array.sort {|x, y| ...}
List.Contains Array.include?
List.IndexOf Array.index
List.LastIndexOf Array.rindex
List.Reverse Array.reverse
Stirng.Join Array.join
List.Sort Array.sort
Array.uniq
Array.flatten

ハッシュ

関連するドキュメント
MSDN Rubyリファレンス
System.Collections.Generic.Dictionary Hash
C# Ruby
C# Ruby
new Dictionary<string, int>() {{"a", 1}, {"b", 2}, {"c", 3}} {'a' => 1, 'b' => 2, 'c' => 3}
foreach (var pair in Dictionary) for key, val in Hash
foreach (var pair in Dictionary) Hash.each, Hash.each_pair
foreach (var key in Dictionary.Keys) Hash.each_key
foreach (var value in Dictionary.Values) Hash.each_value
Dictionary.Count Hash.length, Hash.size
Dictionary.Keys Hash.keys
Dictionary.Values Hash.values
Dictionary.ContainsKey Hash.key?, Hash.has_key?, Hash.include?
Dictionary.ContainsValue Hash.value?
Dictionary[key], Dictionary.TryGetValue(key, out value) Hash.fetch(key), Hash[key]
Hash.key(value)
Hash.merge(hash)

日付と時刻

関連するドキュメント
MSDN Rubyリファレンス
System.DateTime
System.DateTimeOffset
Time
C# Ruby
C# Ruby
DateTime.Now Time.now
DateTime.Ticks, (long)DateTime.Now.Substract(new DateTime(1970, 1, 1)).TotalSeconds Time.tv_sec
(new DateTime(1970, 1, 1)).AddSeconds(time) Time.at(time)
DateTime.Parse, DateTime.TryParse Time.parse
DateTime.ParseExact, DateTime.TryParseExact Time.strftime
new DateTime(..., DateTimeKind.Utc) Time.gm(...), Time.utc(...)
new DateTime(..., DateTimeKind.Local) Time.local(...), Time.mktime(...)
DateTime.ToUniversalTime Time.getgm, Time.getutc
DateTime.ToLocalTime Time.getlocal
DateTime.Hour, DateTime.Minute, DateTime.Second Time.hour, Time.min, Time.sec
DateTime.Year, DateTime.Month, DateTime.Day Time.year, Time.month, Time.day
DateTime.DayOfWeek Time.wday
DateTime.DayOfYear Time.yday
DateTime.ToString("z") Time.zone
Time.usec
DateTime.Millisecond
DateTime.ToString("ddd, d MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture) + " " +
DateTime.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", "")
Time.rfc2822, Time.rfc822
DateTime.ToString("r") Time.httpdate
DateTime.ToString("s")
XmlConvert.ToString(DateTime, XmlDateTimeSerializationMode.Local)
Time.iso8601, Time.xmlschema

IOストリーム

関連するドキュメント
MSDN Rubyリファレンス
System.Console
System.IO.Stream
System.IO.TextReader
System.IO.TextWriter
IO
組み込み変数
組み込み関数
C# Ruby
C# Ruby
Console.Write p, print
Console.WriteLine print String + "\n"
Console.In STDIN, $stdin
Console.Out STDOUT, $stdout
Console.Error STDERR, $stderr
Console.SetIn(stream) $stdin = stream
Console.SetOut(stream) $stdout = stream
Console.SetError(stream) $stderr = stream
new FileStream(file) open(file)
using (var reader = new TextReader(file)) {while(!eof) reader.ReadLine()...;} IO.foreach(file)
using (var reader = new TextReader(file)) {reader.ReadToEnd();} IO.readlines(file)
using (var reader = new TextReader(file)) {reader.Read(length);} IO.read(file, length)
while(!eof) TextReader.ReadLine() IO.each_line
while(!eof) Stream.ReadByte IO.each_byte
TextReader.ReadLine() IO.gets, IO.readline
Stream.Write IO.print, IO.write
Stream.WriteByte IO.putc
TextWriter.Write IO.printf

ファイルシステム

関連するドキュメント
MSDN/Mono Documentation Rubyリファレンス
System.IO
Mono.Unix.Native
File
Dir
fileutils
FileTest
C# Ruby
C# Ruby
File.Exists, Directory.Exists File.exist?
File.Exists File.file?, FileTest.file?
Directory.Exists File.directory?, FileTest.directory?
Path.GetFileName File.basename
Path.GetDirectoryName File.dirname
Path.GetExtension File.extname
Path.GetFileNameWithoutExtension(path) File.basename(path, '.*')
Path.GetFullPath File.expand_path
Directory.GetFileSystemEntries(dir) Dir.entries(path)
Directory.GetFileSystemEntries(dir, pattern) Dir.glob(pattern)
Directory.GetFiles(dir, pattern, SearchOption.TopDirectoryOnly) Dir.glob("#{dir}/*/#{pattern}")
Directory.GetFiles(dir, pattern, SearchOption.AllDirectories) Dir.glob("#{dir}/**/#{pattern}")
File.split
File.Copy FileUtils.cp, FileUtils.cp_r, FileUtils.copy
File.Delete File.delete, File.unlink, FileUtils.rm
File.Move File.rename
FileStream.SetLength File.truncate
FileInfo.Length File.size
Directory.CreateDirectory Dir.mkdir, FileUtils.mkdir(親ディレクトリが無い場合は失敗)
FileUtils.mkdir_p, FileUtils.makedirs(親ディレクトリも含めて作成)
Directory.Delete Dir.rmdir, FileUtils.rm_r
File.GetLastAccessTime, Directory.GetLastAccessTime File.atime
File.ctime
File.GetLastWriteTime, Directory.GetLastWriteTime File.mtime
File.GetCreationTime, Directory.GetCreationTime
File.identical?
FileUtils.touch
Directory.SetCurrentDirectory, Environment.CurrentDirectory Dir.chdir, FileUtils.cd
Directory.GetCurrentDirectory, Environment.CurrentDirectory Dir.pwd, Dir.getwd, FileUtils.pwd
new FileInfo, new DirectoryInfo, Mono.Unix.Native.Syscall.stat(Mono.Posix.dll) File.stat
Mono.Unix.Native.Syscall.chmod(Mono.Posix.dll) File.chmod
Mono.Unix.Native.Syscall.chown(Mono.Posix.dll) File.chown
Mono.Unix.Native.Stat.st_mode(Mono.Posix.dll) File.executable?
Mono.Unix.Native.Stat.st_mode(Mono.Posix.dll) File.readable?
Mono.Unix.Native.Stat.st_mode(Mono.Posix.dll) File.writable?
Mono.Unix.Native.Syscall.opendir(Mono.Posix.dll) Dir.open

数値演算

関連するドキュメント
MSDN Rubyリファレンス
System.Math
System.Double
Math
Float
C# Ruby
C# Ruby
Math.Pow(3, 2) 3 ** 2
Math.E Math::E
Math.Pi Math::PI
Double.NaN.Equals() Float.nan?
Double.PositiveInfinity.Equals Float.infinite? == 1
Double.NegativeInfinity.Equals Float.infinite? == -1
Math.Truncate Float.truncate
Math.Round Float.round
Math.Ceiling Float.ceil
Math.Floor Float.floor
Math.Exp Math.exp
Math.Sin, Math.Cos, Math.Tan Math.sin, Math.cos, Math.tan
Math.Log10 Math.log10
Math.Log Math.log
Math.Log(x, n) Math.log(x) / Math.log(n)

プロセス

MSDN Rubyリファレンス
System.Diagnostics.Process Process
組み込み関数
open3
C# Ruby
C# Ruby
Process.Start("echo 'hoge'") system("echo 'hoge'")
Process.Start("echo 'hoge'", ProcessStartInfo.RedirectStandardOutput) str = `echo 'hoge'`
ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, ProcessStartInfo.RedirectStandardError Open3.popen3
Process.Start, AppDomain.CreateInstance fork
Environment.Exit exit

スレッド

関連するドキュメント
MSDN Rubyリファレンス
System.Threading.Thread Thread
C# Ruby
C# Ruby
Thread.Sleep(1) sleep(0.001)
Thread.Sleep(1000) sleep(1)
(new Thread(ThreadStart)).Start Thread.new {...}, Thread.start {...}, Thread.fork {...}
(new Thread(ParameterizedThreadStart)).Start Thread.new(param1, param2) {...}
Thread.Join Thread.join
Thread.Abort Thread.kill, Thread.terminate
Thread.Suspend Thread.Stop
Thread.Resume Thread.Run

その他・未整理

C# Ruby
C# Ruby
Uri class URI Module
Convert.ToBase64String Base64.encode64
Convert.FromBase64String Base64.decode64
MD5CryptoServiceProvider.ComputeHash Digest::MD5.digest
SHA1CryptoServiceProvider.ComputeHash Digest::SHA1.digest
new SmtpClient Net::SMTP.start
new WebClient Net::HTTP.start
WebClient.OpenRead open(URI) (require 'open-uri')
HttpUtility.HtmlEncode CGI.escapeHTML
HttpUtility.HtmlDecode CGI.unescapeHTML
HttpUtility.UrlPathEncode CGI.escape
HttpUtility.UrlEncode (System.Web.dll), Uri.EscapeDataString (System.dll) URI.escape
HttpUtility.UrlDecode (System.Web.dll), Uri.UnescapeDataString (System.dll) URI.unescape
SecurityElement.Escape CGI.escapeHTML(String.gsub("'", '"'))