Ruby関連のことを調べてみた2020年01月26日

Ruby関連のことを調べてみた2020年01月26日

#Ruby – Tempfile write rewind close unlink – lifecycle

“`rb
tempfile = Tempfile.new
# => #

tempfile.write(‘ABC’)
# => 3

tempfile.read
# => “”

File.read(tempfile.path)
# => “ABC”

tempfile.rewind
# => 0

tempfile.read
# => “ABC”

tempfile.close
# => nil

File.read(tempfile.path)
# => “ABC”

tempfile.read
# IOError: closed stream
# from /Users/yumainaura/.rbenv/versions/2.5.3/lib/ruby/2.5.0/delegate.rb:349:in `read’

tempfile.unlink
# => true

File.read(tempfile.path)
#

元記事を表示

#Ruby で SJIS のCSVファイルを書き込む、読み込む

encodingフラグを使って色々とやる
stringに対しての直接のencodeは必要なさそう

“`rb
File.write(‘tmp/sjis.csv’, “あ,い,う\nえ,お,か”, encoding: Encoding::SJIS)
# => 17

File.read(‘tmp/sjis.csv’, encoding: Encoding::SJIS)
# => “あ,い,う\nえ,お,か”

CSV.read(‘tmp/sjis.csv’, encoding: Encoding::SJIS)
# => [[“あ”, “い”, “う”], [“え”, “お”, “か”]]

CSV.open(‘tmp/sjis2.csv’, ‘w’, encoding: Encoding::SJIS) do |row|
row << ['か', 'き', 'く'] row << ['け', 'こ', 'さ'] end # => <#CSV io_type:File io_path:"tmp/sjis2.csv" encoding:UTF-8 lineno:2 col_sep

元記事を表示

#Ruby – UTF8 SJIS でのファイル書き込み、読み込みの挙動を試す

“`rb

# ———————————————————–
# String のエンコード
# ———————————————————–

# 日本語を文字列としてエンコードした結果
‘あ’.encode(Encoding::SJIS)
# => “\x{82A0}”

# String的にUTf_8にエンコードし直すと、UTf_8に戻る
“あ”.encode(Encoding::SJIS).encode(Encoding::UTF_8)
# => “あ”

# ———————————————————–
# A. UTF8の文字列を UTF_8指定で ファイルに書き込む
# ———————————————————–
File.write(‘tmp/utf8.txt’, ‘あ’,

元記事を表示

#Ruby の tr でバックスラッシュと他の文字が同時に置換できない?

Wanna replace in string

Repladce backslash with A
Repladce colon with X

“`rb
puts ‘ \\ : ‘
# \ :

# Only backslash replace
# It works
puts ‘ \\ : ‘.tr(‘\\’, ‘A’)
# A :

# Replace backslash and other calacter one time
# It does not work
puts ‘ \\ : ‘.tr(‘\\:’, ‘AX’)
# \ A

# Above case maybe same as this
# Only colon replacing
puts ‘ \\ : ‘.tr(‘:’, ‘AX’)
# \ A

# Use expression triple backslash as backslash
# It works
puts ‘ \\ : ‘.tr(‘\\\:’, ‘AX’)
# A X

# It works
# backslash at last charac

元記事を表示

#Ruby tr replace backslash and other character netime

Wanna replace in string

Repladce backslash with A
Repladce colon with X

“`rb
puts ‘ \\ : ‘
# \ :

# Only backslash replace
# It works
puts ‘ \\ : ‘.tr(‘\\’, ‘A’)
# A :

# Replace backslash and other calacter one time
# It does not work
puts ‘ \\ : ‘.tr(‘\\:’, ‘AX’)
# \ A

# Above case maybe same as this
# Only colon replacing
puts ‘ \\ : ‘.tr(‘:’, ‘AX’)
# \ A

# Use expression triple backslash as backslash
# It works
puts ‘ \\ : ‘.tr(‘\\\:’, ‘AX’)
# A X

# It works
# backslash at last charac

元記事を表示

写真整理のためRubyでファイル名変更と年月フォルダへ移動

# はじめに

過去、撮りためた写真ファイル、行き当たりばったりに保管してきたのでフォルダ構成が汚い。また、カメラのメーカーごとにファイルの命名規則もバラバラでしたので、整理してみました。

ファイル名をyymmdd_HHMMSS_連番.jpgに変更し、
YYMMフォルダに移動します。

# 環境

* Ubuntu 18.04.3 LTS
* ruby 2.5.1

# ソースコード

“`ruby
require ‘fileutils’

#————————————————-
# カレント配下のファイル※1に対し以下を行う
# * ファイル名変更 yymmdd_HHMMSS_連番.jpg ※2
# * pic/年月フォルダへ移動
#
# ※1 jpg, jpeg, JPG
# ※2 連番はファイル名がかぶっている場合に振る
#————————————————-

cur = Dir.pwd + ‘/’
i = 0 # 連番用
j = 0 # 連

元記事を表示

irbのJupyter wrapper kernelをpoetryを使ってPyPIで公開する

タイトルの作業を行っていきます。
irbはRubyのREPLです。

先に出来上がったものを見せると
https://github.com/PyDataOsaka/irb_kernel
になります。

ここに至るまでに下記を行いました。

### poetryでパッケージソースの雛形を作成

“`
pip install poetry
poetry new irb_kernel
cd irb_kernel
poetry add pexpect
poetry add notebook
“`

### irb_kernel下にコードを追加

@antimon2 さんの [Jupyter の Egison 簡易カーネルを自作してみた。](https://qiita.com/antimon2/items/7d9c084b142d38b67b1f)

https://github.com/takluyver/bash_kernel
を真似ました。

https://github.com/PyDataOsaka/irb_kernel/blob/master/irb_kernel/instal

元記事を表示

困ったらググれ

どうも、[**momotaro**](https://twitter.com/1992_momotaro)です。初めまして。

TECH::EXPERT受講初めたことがきっかけで、ブログはじめました。
自己学習(アウトプット)の為に投稿していきます。

今週月曜からプログラミング初心者として学習を始めて、この一週間で学んだ大きなこと。
それはタイトルにある通り、
### 分からないコードが出てきたり、エラーが出てきたらGoogleさんに遠慮なく質問しよう!
・・・ということですね。

これはTECH::EXPERTのカリキュラムにもきちんと書いてあります。

この教えが意味するものは
###『”自己解決能力”を身につける』

だと思います。大切なのは、なぜその問題が起こるのかを理解すること。そして大事なのは、いかにその問題をいち早く解決できるか・・・。
実際現場の方でもググることはよくあるそうです。

なので、これからは良い検索方法やわかりやすい解説サイト、ブログなどあれば模索していきたいと思います。

また自分が新しい解説など思いついたり発見した場合は発信していきます。

最後に自

元記事を表示

RSpecで利用するFactoryBotの導入

#FactoryBot

FactoryBotはテスト用データの作成をサポートするgemであり、利用するとテスト用のデータを簡単に作成し、テストから呼び出すことができる。

早速Gemfileに’factory_bot_rails’を記述しbundle install を実行しよう

“`ruby
# Gemfile
group :development, :test do
gem ‘rspec-rails’
gem ‘factory_bot_rails’, ‘~> 4.11’
end
“`

##FactoryBotでテストデータを作成できるよう準備

###Userのファクトリを作成
一例としてuserのファクトリを作成していきます。

“`ruby
# spec/factories/users.rb
FactoryBot.define do
factory :user do
sequence(:email) { |n| “tester#{n}@example.com” } #重複を防ぐためsequenceを使う
password { ‘passw

元記事を表示

【Ruby】Qiita 週間いいね数ランキング【自動更新】

# 他のタグ

– [Python](https://qiita.com/kou_pg_0131/items/9d7f2ffeafb36cf59a77)
– [JavaScript](https://qiita.com/kou_pg_0131/items/eaa7ac5b62a0a723edbb)
– [AWS](https://qiita.com/kou_pg_0131/items/e24b6279326a462d456c)
– [Ruby](https://qiita.com/kou_pg_0131/items/72c3d2e896bdc3e1a6b3)
– [Rails](https://qiita.com/kou_pg_0131/items/93b9e7f7d143e9ce650e)
– [Docker](https://qiita.com/kou_pg_0131/items/ae11fca7d2eba445b037)
– [Vue.js](https://qiita.com/kou_pg_0131/items/2774e02c6eea5c830d99)
– [PHP](htt

元記事を表示

attr_accessorに関して

# はじめに
Ruby初心者ですが、attr_accsessorの内容が最初イマイチ理解できず。
徐々に理解が出来たので纏めてみました!

※「この表現が変だよ」などあればコメントお願いします。

# attr_accessorとは?
@nameなどのインスタンス変数をクラス外から呼び出し、書き込みを定義するメソッド。

# attr_reader, attr_writerとの違い
attr_reader = 呼び出し専用
attr_writer = 書き込み専用

attr_accessor = 両方の機能を兼ね備えている

# インスタンス変数とは
インスタンスの中で値を保持する為の変数。

例)
user1 = User.new
Userクラスをnewすることでuser1というインスタンスが作られる。
クラスの中で定義されている「@変数名」がインスタンス変数となる。

# 使い方
インスタンス変数の内容を、呼び出しと書き込みの両方を行いたい場合はattr_accessorを選択する。

# 使用例
“`ruby

class User
attr_accessor :nam

元記事を表示

テスト駆動開発から始めるRuby入門 ~ソフトウェア開発の三種の神器を準備する~

# エピソード2

## 初めに

この記事は [テスト駆動開発から始めるRuby入門 ~2時間でTDDとリファクタリングのエッセンスを体験する~](https://qiita.com/k2works/items/83741e3e2d2579d748d6) の続編です。

## 自動化から始めるテスト駆動開発

エピソード1ではテスト駆動開発のゴールが **動作するきれいなコード** であることを学びました。では、良いコードを書き続けるためには何が必要になるでしょうか?それは[ソフトウェア開発の三種の神器](https://t-wada.hatenablog.jp/entry/clean-code-that-works)と呼ばれるものです。

> 今日のソフトウェア開発の世界において絶対になければならない3つの技術的な柱があります。
> 三本柱と言ったり、三種の神器と言ったりしていますが、それらは
>
> – バージョン管理
>
> – テスティング
>
> – 自動化
>
> の3つです。
>
> — https://t-wada.hatenablog.jp/

元記事を表示

Leetcode 938: Range Sum of BST

“`ruby
#Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
#The binary search tree is guaranteed to have unique values.
#The number of nodes in the tree is at most 10000.
#The final answer is guaranteed to be less than 2^31.

require ‘test/unit’

# https://leetcode.com/problems/range-sum-of-bst/

class RangeSumOfBst < Test::Unit::TestCase def test_range_sum_bst # TODO: Add test end def range_sum_bst(root, l, r

元記事を表示

Leetcode 617: Merge Two Binary Trees

“`ruby
require ‘test/unit’
require ‘pry’
class MergeTwoBinaryTrees < Test::Unit::TestCase # https://leetcode.com/problems/merge-two-binary-trees/ # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} t1 # @param {TreeNode} t2 # @return {TreeNode} # def test_calc #TODO: Add test case end def merge_tr

元記事を表示

Leetcode 1108: Defanging an IP Address

“`ruby
require ‘test/unit’
require ‘pry’
class DefanginAnIpAddress < Test::Unit::TestCase # https://leetcode.com/problems/defanging-an-ip-address/ # Qiita: def test_defang_i_paddr input = "1.1.1.1" output = "1[.]1[.]1[.]1" assert_equal(output, defang_i_paddr(input)) input = "255.100.50.0" output = "255[.]100[.]50[.]0" assert_equal(output, defang_i_paddr(input)) end def defang_i_paddr(address) address.gsub('.', '[.]') end end

元記事を表示

Leetcode: Most Common Word

“`{ruby}

require ‘test/unit’
require ‘pry’
class MostCommonWord < Test::Unit::TestCase #https://leetcode.com/problems/most-common-word/submissions/ def test_calc paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] output = "ball" assert_equal(output, solution(paragraph, banned)) paragraph = "a, a, a, a, b,b,b,c, c" banned = ["a"] output = "b" assert_equal(output, solution(paragraph, banned)) end def solution(paragra

元記事を表示

Leetcode: Construct String from Binary Tree

“`{ruby}
require ‘test/unit’
require ‘pry’
class ConstructStringFromBinaryTree < Test::Unit::TestCase #https://leetcode.com/problems/construct-string-from-binary-tree/ def test_calc # You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. # The null node needs to be represented by empty parenthesis pair "()". # And you need to omit all the empty parenthesis pairs that # don't affect the one-to-one mapping re

元記事を表示

Leetcode: Decompress Run Length Encoded List

“`{ruby}
require ‘test/unit’
require ‘pry’
class DecompressRunLengthEncodedList < Test::Unit::TestCase # Qiita: posted #https://leetcode.com/problems/decompress-run-length-encoded-list/ def test_calc #We are given a list nums of integers representing a list compressed with run-length encoding. #Consider each adjacent pair of elements [a, b] = [nums[2 * i], nums[2 * i + 1]] (with i >= 0).For each such pair, there are a elements with value b in the decompressed list.
#Return

元記事を表示

Docker-composeでbundle installしてるのにgemの内容反映されないんですけど

#注意事項
完全に個人用メモです。公式情報でもなんでもありません。ググってこの記事に来てしまった方はお気をつけください。違っていたら即直しますのでガンガンご指摘ください。(個人用メモなので追加もしていきます)

## そもそもbundle installしたらサーバー再起動しろや

なので、gemfile編集してbundle installしたら以下のコマンド打てば良い(環境によるけど)

`docker-compose restart`・・・コンテナ再起動

そしたらGemの内容が反映されます。

docker勉強不足だって、はっきりわかんだね。

## イメージをビルドしなおしたりコンテナ削除したりしなくて良い

dockerを理解してないと以下のようなコマンドを打ち始めます

`docker-compose build`・・・イメージビルド

`docker-compose up -d`・・・コンテナ作成&起動

結果、コンテナが増えまくるわけです。(えぇ。。。)

コンテナやたら多いと思ったら原因これかよw(錯乱)

まあこの方法でも解決できるんですけどね。。

元記事を表示

Docker + rails + mysqlで開発環境を構築

## はじめに
今回は、railsの開発環境をDocker+rails+mysqlで用意します。

## 構成
構成はローカルのMacにDockerを立て、webとdbコンテナをdocker-composeで管理します。

![スクリーンショット 2020-01-25 10.06.34.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/134365/d3e1e249-5fbe-f130-0276-c0b2ebb0e8ea.png)

## 開発環境
Docker 19.03.5
Ruby 2.6.5
Rails 5.2.4
MySQL 5.7.29

## 前提条件
Macを利用

## Docker Desktopをインストール

まずは、ローカルのMacにDocker Desktopをインストールします。

https://www.docker.com/get-started

![スクリーンショット 2020-01-22 0.09.31.png](https://qiita-image-store

元記事を表示

OTHERカテゴリの最新記事