2008-03-31T06:34:44の更新内容

programming/ruby/compare_with_cs/index.wiki.txt

current previous
1,239 0,0
+
${smdncms:tags,C#,対比}
+
*C#とRubyの対比表
+
C#とRubyの対比・比較表です。 「C#で言うところの…」と「Rubyで言うところの…」に対応する記述を対比表としてまとめたものです。 Rubyスクリプトを書いているときに「C#で言うところのアレはRubyではどう書くんだっけ」ということが多いので、すぐに参照できるようよく使う部分を中心にまとめてあります。
+

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

          
+
**文字列
+
|C#|Ruby|h
+
|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'|
+
|N/A|String.sub('foo', 'bar')|
+
|String.Replace("foo", "bar")|String.gsub('foo', 'bar')|
+
|TextReader.ReadLine|String.chomp|
+
|N/A|String.chop|
+
|int.Parse|String.to_i|
+
|float.Parse|String.to_f|
+
|String.Copy(String)|String.dup|
+
|N/A|String.count('foo')|
+
|String.Trim|String.strip|
+
|String.TrimStart|String.lstrip|
+
|String.TrimEnd|String.rstrip|
+
|new String('f', n)|'f' * n|
+
|N/A|'foo' * n|
+
|String.Split|String.split|
+
|N/A|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(&br;Encoding.Unicode.GetBytes(String))|String.tosjis|
+
|C#|Ruby|f
+

          
+
***ヒアドキュメント
+
C#
+
 string str = @"line1
+
 line2
+
 line3";
+

          
+
Ruby
+
 str = <<END_OF_STR
+
 line1
+
 line2
+
 line3
+
 END_OF_STR
+

          
+
**正規表現
+
|C#|Ruby|h
+
|Regex.IsMatch, Regex.Match|=~ /.../|
+
|Regex.Matches|String.scan(Regexp)|
+
|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]|
+
|C#|Ruby|f
+

          
+
**コレクション
+
|C#|Ruby|h
+
|new[] {0, 1, 2, 3, 4}|[0, 1, 2, 3, 4]|
+
|foreach|for item in array|
+
|foreach|array.each|
+
|List[0]|Array.first|
+
|List[List.Length - 1]|Array.last|
+
|List.Length|Array.length, Array.size|
+
|List.FindAll(delegate(T item) {return item != null;}).Length|Array.nitems|
+
|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.Contains|Array.include?|
+
|List.IndexOf|Array.index|
+
|List.LastIndexOf|Array.rindex|
+
|List.Reverse|Array.reverse|
+
|Stirng.Join|Array.join|
+
|List.Sort|Array.sort|
+
|N/A|Array.uniq|
+
|N/A|Array.flatten|
+
|C#|Ruby|f
+

          
+
**ハッシュ
+
|C#|Ruby|h
+
|new Dictionary<string, int>() {{"a", 1}, {"b", 2}, {"c", 3}}|{'a' => 1, 'b' => 2, 'c' => 3}|
+
|foreach|for key, val in Hash|
+
|foreach|Hash.each, Hash.each_pair|
+
|foreach|Hash.each_key|
+
|foreach|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]|
+
|N/A|Hash.key(value)|
+
|N/A|Hash.merge(hash)|
+
|C#|Ruby|f
+

          
+
**日付と時刻
+
|C#|Ruby|h
+
|DateTime.Now|Time.now|
+
|DateTime.Ticks,.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|
+
|N/A|Time.usec|
+
|DateTime.Millisecond|N/A|
+
|DateTime.Now.ToString("ddd, d MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture) + " " + &br;DateTime.Now.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", "")|Time.rfc2822, Time.rfc822|
+
|DateTime.Now.ToString("r")|Time.httpdate|
+
|DateTime.Now.ToString("s")|Time.iso8601, Time.xmlschema|
+
|C#|Ruby|f
+

          
+
**IOストリーム
+
|C#|Ruby|h
+
|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|
+
|using|
+
|using|
+
|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|
+
|C#|Ruby|f
+

          
+
**ファイルシステム
+
|C#|Ruby|h
+
|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|N/A|
+
|Path.GetFullPath|File.expand_path|
+
|Directory.GetFileSystemEntries(dir)|Dir.entries(path)|
+
|Directory.GetFileSystemEntries(dir, pattern)|Dir.glob(pattern)|
+
|N/A|File.split|
+
|File.Delete|File.delete, File.unlink|
+
|File.Move|File.rename|
+
|FileStream.SetLength|File.truncate|
+
|FileInfo.Length|File.size|
+
|Directory.CreateDirectory|Dir.mkdir|
+
|Directory.Delete|Dir.rmdir|
+
|File.GetLastAccessTime, Directory.GetLastAccessTime|File.atime|
+
|N/A|File.ctime|
+
|File.GetLastWriteTime, Directory.GetLastWriteTime|File.mtime|
+
|File.GetCreationTime, Directory.GetCreationTime|N/A|
+
|N/A|File.identical?|
+
|Directory.SetCurrentDirectory, Environment.CurrentDirectory|Dir.chdir|
+
|Directory.GetCurrentDirectory, Environment.CurrentDirectory|Dir.pwd, Dir.getwd|
+
|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|
+
|C#|Ruby|f
+

          
+
**数値演算
+
|C#|Ruby|h
+
|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)|
+
|C#|Ruby|f
+

          
+
**プロセス
+
|C#|Ruby|h
+
|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|
+
|C#|Ruby|f
+

          
+
**その他・未整理
+
|C#|Ruby|h
+
|Uri class|URI Module|
+
|Convert.ToBase64String|Base64.encode64|
+
|Convert.FromBase64String|Base64.decode64|
+
|MD5CryptoServiceProvider.ComputeHash|Digest::MD5.digest|
+
|new SmtpClient|Net::SMTP.start|
+
|new WebClient|Net::HTTP.start|
+
|HttpUtility.HtmlEncode|CGI.escapeHTML|
+
|HttpUtility.HtmlDecode|CGI.unescapeHTML|
+
|HttpUtility.UrlPathEncode|CGI.escape|
+
|HttpUtility.UrlEncode|URI.escape|
+
|HttpUtility.UrlDecode|URI.unescape|
+
|SecurityElement.Escape|CGI.escapeHTML(String.gsub("'", '&quot;'))|
+
|C#|Ruby|f
+